更改 WCF 中的默认日期序列化 [英] Change default date serialization in WCF

查看:30
本文介绍了更改 WCF 中的默认日期序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何要更改 WCF 中 DateTime 的默认 JSON 序列化/反序列化?

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

目前,DateTime 被序列化为 /Date(1372252162657+0200)/ 格式,这应该没问题,但是当我的服务器不在 UTC(我不能改变).

Currently, DateTime are serialized into the /Date(1372252162657+0200)/ format, which should've been fine but I'm running into issues when my server is not in UTC (which I can't change).

此服务正在处理的所有日期/时间数据均采用 UTC 格式.当服务器处于 UTC 时,一切正常.但是,暂存/生产环境设置为 GMT+1(Paris) 并且序列化程序假设日期/时间在 GMT+1,完全忽略属性 Kind.因此,正如您所期望的那样,调用 DateTime.SetKind() 并将其设置为 UTC 将不起作用.实际上,序列化时间延迟了一个小时.

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 Kind. So as you'd expect calling DateTime.SetKind() and setting it to UTC will not work. In effect, the serialized times are delayed by an hour.

我可以进行双向日期对话(它在反序列化时也做出相同的假设,因此它总是 GMT+1)日期对话:UTC 到/从服务器时间,但这太乏味了.所以我想也许我可以覆盖默认的序列化行为.

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.

推荐答案

是的,这可以使用名为消息格式器"

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

但是 Message Formatter 会很困难并且超出了在堆栈溢出时在这里解释的范围.您可以参考 WCF 扩展性:消息格式化程序

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

如果您不想弄乱这个,那么可以使用 hack.

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

将每个方法的返回类型设置为Stream.

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()));
        }

这里 ToJson() 是我自己的扩展方法,它使用 NewtonSoft 库将对象转换为 json 字符串.

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

WCF 将跳过用于序列化的流输出,并将其按原样传递给您的客户端.

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

希望你能得到答案.

这篇关于更改 WCF 中的默认日期序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆