我正在尝试从服务器向客户端(.Net)发送请求,该客户端在特定于文化的环境中运行,该环境会影响特殊时区的日期。
我从服务器发送具有未指定类型的日期,以避免在客户端检索时进行转换。基本上我只是在服务器端转换它:
DateTime dateToSend = DateTime.SpecifyKind(serverSideDate, DateTimeKind.Unspecified);
问题是当为客户端使用JsonProtocol时,日期没有被转换并且正在被正确处理,而对于MessagePackProtocol,客户端和服务器端的相同代码以完全不同的方式工作 - 它将日期转换为客户端上的文化特定时区。 。
如何防止这种转换,没有一些黑客解决方案,比如将日期作为字符串传递。
更新: 正如Shaun建议的那样,我已经在客户端和服务器端以这种方式配置了MessagePack,但不幸的是它仍然无法正常工作:
.AddMessagePackProtocol(options =>
options.FormatterResolvers = new List<MessagePack.IFormatterResolver>()
{
StandardResolver.Instance,
NativeDateTimeResolver.Instance
})
问题是kind is lost with the MessagePackProtocol。
DateTime
被序列化为MessagePack时间戳格式,它序列化/反序列化UTC并丢失Kind
信息。
该说明继续说我们可以通过使用NativeDateTimeResolver
来改变它(尽管有一些限制)。
如果你使用
NativeDateTimeResolver
序列化本机DateTime
二进制格式,它可以保持Kind
信息,但不能与其他平台通信。
正如Chris和Panagiotis所说,最好使用DateTimeOffset
。官方Microsoft documentation says this:
应将DateTimeOffset视为应用程序开发的默认日期和时间类型。
StackOverflow比较DateTime vs DateTimeOffset还有很多有用的信息。