Change default date serialization in WCF

前端 未结 5 767
-上瘾入骨i
-上瘾入骨i 2020-12-03 07:39

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

Currently, DateTime are serialized into the /Date(1372252162657+0

5条回答
  •  星月不相逢
    2020-12-03 08:39

    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.

    e.g.

            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.

提交回复
热议问题