Skip to main content
 首页 » 编程设计

c#之Web 服务的日期格式问题

2024年04月30日48jiqing9006

我有一个带有输入参数的网络服务。 WSDL中的相关XSD如下

当我在 Visual Studio 中将此 WSDL 添加为服务引用时,它生成了一个具有相应字段的类,如 System.DateTime。下面是为 WSDL 添加的 Reference 类中的字段示例

private System.Nullable<System.DateTime> startDateField; 

我创建客户端的服务绑定(bind)是下面的 CustomBinding

 protected CustomBinding GetCustomBinding() 
    { 
        var customBinding = new CustomBinding() { Name = "CustomBinding" }; 
 
        customBinding.Elements.Add(new TextMessageEncodingBindingElement() { MessageVersion = MessageVersion.Soap11 }); 
        var securityBindingElement = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); 
        securityBindingElement.AllowInsecureTransport = true; 
        securityBindingElement.EnableUnsecuredResponse = true; 
        securityBindingElement.IncludeTimestamp = false; 
        customBinding.Elements.Add(securityBindingElement); 
        customBinding.Elements.Add(new HttpTransportBindingElement()); 
 
        return customBinding; 
    } 

我的 C# 代码分配输入

myobject.input.endDate = Convert.ToDateTime(endDate); 

分配输入值后,我调用了一个 Web 方法,在 Fiddler 中看到 Request 中缺少所有日期参数。

我尝试在 SoapUI 中进行测试。看起来服务需要格式为 yyyy-MM-dd 的日期,尽管类型是日期。仅当我以 yyyy-MM-dd 格式提供日期时,网络服务才返回数据。

我不确定这是否与网络服务的预期日期格式有关。显然,我无法以 yyyy-MM-dd 格式发送,因为 .Net 生成的引用类具有 DateTime 但没有 string 数据类型。

我试图强行将 Specified 设置为 true

myobject.input.endDate = Convert.ToDateTime(endDate).Date; 
myobject.input.endDateSpecified = true; 

我收到以下错误:

A value was being set that exceeded the maximum allowable field length. 

现在,我怀疑 Web 服务需要 Date 但 .Net 正在尝试发送可能会延长其长度的 DateTime

请您参考如下方法:

看起来我的上一个代码有效,但错误是由于另一个字段造成的。

myobject.input.endDate = Convert.ToDateTime(endDate).Date; 
myobject.input.endDateSpecified = true;