Mel Mel - 1 year ago 194
C# Question

Change default date serialization in WCF

Is there anyway to change the default JSON serialization/deserialization of DateTime in WCF?

Currently, DateTime are serialized into the

format, which should've been fine but I'm running into issues when my server is not in UTC (which I can't change).

All date/time data that is being processed by this service is in UTC format. Everything works when the server is in UTC. However, the staging/prod environments are set to GMT+1(Paris) and the serializer is assuming that the dates/times are in GMT+1, completely ignoring the attribute
. So as you'd expect calling
and setting it to UTC will not work. In effect, the serialized times are delayed by an hour.

I can either do two-way date conversations (it also makes the same assumption when deserializing so its always GMT+1) conversation of dates: UTC to/from server time, but this is to tedious. So I thought maybe I could just override the default serialization behavior.

Answer Source

Yes, this can be done using the concept called "Message Formatters"

But Message Formatter would be tough and out of scope to explain here on stack overflow. You can refere WCF Extensibility : Message Formatters

If you don't want mess up with this then an hack is available.

Set the return type of each method to Stream.


        public Stream GetStaticData()
            var objTobeReturned = something;
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return new MemoryStream(Encoding.UTF8.GetBytes(objTobeReturned.ToJson()));

here ToJson() is my own extension method which converts object into json string using NewtonSoft library.

WCF will skip the stream output for serializing and will pass it to your client as it is.

I hope you got your answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download