In WebServices, TimeSpan cannot be used as a system TimeSpan parameter. A new TimeSpan class is generated on the client.
I. Problem Reproduction
Create a Web Method with TimeSpan as the parameter:
1: [WebMethod]
2: public string HelloWorld(TimeSpan span)
3: {
4: return "Hello World";
5: }
6:
View the WSDL file and see the following content:
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" />
When the client references Web Services, a new TimeSpan class is generated:
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: }
The method can only use the TimeSpan generated above:
Ii. Solution
Extended 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: }
Pass TimeSpan through TimeSpan:
1: [WebMethod]
2: public string HelloWorld(TimeSpanEx span)
3: {
4: return "Hello World";
5: }
6:
Client example:
1: WebService1SoapClient client = new WebService1SoapClient();
2: TimeSpanEx span = new TimeSpanEx();
3: span.TimeSpan = new TimeSpan(1, 2, 3).ToString();
4: client.HelloWorld(span);
5:
The TimeSpan result obtained by the server: