我正在尝试将请求从服务器发送到在特定文化环境中运行的客户端(.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
is serialized to MessagePack Timestamp format, it serialize/deserialize UTC and losesKind
info.
注释继续说我们可以改用 NativeDateTimeResolver
来改变它(尽管有一些限制)。
If you use
NativeDateTimeResolver
serialized nativeDateTime
binary format and it can keepKind
info but cannot communicate other platforms.
正如 Chris 和 Panagiotis 所提到的,最好使用 DateTimeOffset
。官方Microsoft documentation says this :
DateTimeOffset should be considered the default date and time type for application development.
StackOverflow 上也有很多有用的信息比较 DateTime vs DateTimeOffset .
关于asp.net-core - 避免 DateTime 转换,同时将其传递给 AspNetCore.SignalR .Net 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52781568/