Search code examples
c#wcfnullabledatacontractserializerdatacontract

How to serialize nullable DateTime in a WCF DataContract?


I am having trouble serializing this thing.

namespace Such.Namespace.Wow
{
    [DataContract(Namespace = "http://very.namespace.uh")]
    public class DogeResponse
    {
        [DataMember]
        public virtual int Foo { get; set; }

        [DataMember]
        public virtual DateTime? ExpiringDate { get; set; }
    }
}

In generated WSDL :

<xs:complexType name="DogeResponse">  
<xs:sequence>
<xs:element minOccurs="0" name="Foo" type="xs:int"/>  
<xs:element minOccurs="0" name="ExpiringDate" nillable="true" type="xs:dateTime"/>  
</xs:sequence></xs:complexType>

But the run-time exception occurs and returns as XML fault:

<SerializationException>
<Message>ValueType 'System.DateTime' cannot be null.</Message>

Yes I saw a "similar" question but it was about ASMX service in somewhat older .NET.

I wonder how to do it in .NET 4.5 WCF service?


Solution

  • It seems like you first had a DateTime (on server and client side) and than you modified the DateTime to a nullable DateTime, but did not update the client side.

    The client side now still expects a DateTime (so no null allowed) but the server is sending a null. Hence the exception.

    Please update the client side service reference.