在WebServices中,TimeSpan不能作为系统的TimeSpan作为参数,在客户端会生成新的TimeSpan类。
一、问题重现
创建一个以TimeSpan为参数的Web Method:
1: [WebMethod]
2: public string HelloWorld(TimeSpan span)
3: {
4: return "Hello World";
5: }
6:
查看WSDL文件,可以看到以下的内容:
1: <s:element name="HelloWorld">
2: - <s:complexType>
3: - <s:sequence>
4: <s:element minOccurs="1" maxOccurs="1" name="span" type="tns:TimeSpan" />
5: </s:sequence>
6: </s:complexType>
7: </s:element>
8: <s:complexType name="TimeSpan" />
客户端引用Web Services会生成新的TimeSpan类:
1: public partial class TimeSpan : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
2:
3: [System.NonSerializedAttribute()]
4: private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
5:
6: [global::System.ComponentModel.BrowsableAttribute(false)]
7: public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
8: get {
9: return this.extensionDataField;
10: }
11: set {
12: this.extensionDataField = value;
13: }
14: }
15:
16: public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
17:
18: protected void RaisePropertyChanged(string propertyName) {
19: System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
20: if ((propertyChanged != null)) {
21: propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
22: }
23: }
24: }
方法只能使用上面生成的TimeSpan:
二、解决方法
扩展TimeSpan:
1: public class TimeSpanEx
2: {
3: [XmlElement(ElementName = "TimeSpan")]
4: public string TimeSpanAsString
5: {
6: get { return TimeSpan != null ? TimeSpan.ToString() : null; }
7: set
8: {
9: TimeSpan span;
10: if (value != null && TimeSpan.TryParse(value, out span))
11: TimeSpan = span;
12: else
13: TimeSpan = new TimeSpan();
14: }
15: }
16: [XmlIgnore]
17: public TimeSpan TimeSpan { get; set; }
18: }
通过TimeSpan传递TimeSpan:
1: [WebMethod]
2: public string HelloWorld(TimeSpanEx span)
3: {
4: return "Hello World";
5: }
6:
客户端使用示例:
1: WebService1SoapClient client = new WebService1SoapClient();
2: TimeSpanEx span = new TimeSpanEx();
3: span.TimeSpan = new TimeSpan(1, 2, 3).ToString();
4: client.HelloWorld(span);
5:
服务端获取的TimeSpan结果: