在WCF更改默认日期系列化 [英] Change default date serialization in WCF

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

问题描述

反正是有改变的DateTime的默认JSON序列化/反序列化的WCF?

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

目前,日期被序列化到 /日期(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(巴黎)和串行被假定的日期/时间以GMT + 1,完全无视属性 。所以,如你所期望调用 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.

推荐答案

是的,这可以通过所谓的概念来完成< STRONG>消息格式化程序

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

不过,消息格式将是艰难的,并超出范围在这里解释的堆栈溢出。
你可以参考, WCF可扩展性:信息格式化

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

下面的toJSON()是使用转换对象转换成JSON字符串我自己的扩展方法NewtonSoft库。

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天全站免登陆