在将 DateTime 传递给 AspNetCore.SignalR .Net 客户端时避免 DateTime 转换

Avoiding DateTime conversion while passing it to AspNetCore.SignalR .Net client

我正在尝试从服务器向客户端 (.Net) 发送请求,客户端 运行 在影响 日期 处于特殊时区的特定文化环境中.

我正在从服务器发送未指定类型的日期,以避免它在客户端检索时被转换。基本上我只是在服务器端像这样转换它:

DateTime dateToSend = DateTime.SpecifyKind(serverSideDate, DateTimeKind.Unspecified);

问题是当客户端使用 JsonProtocol 时,日期没有被转换并且被正确处理,而对于 MessagePackProtocol客户端和服务器端的相同代码以完全不同的方式工作 - 它在客户端将日期转换为特定于文化的时区...

如何防止这种转换,而不需要一些 hack 解决方案,例如将日期作为字符串传递。

更新:
正如 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 loses Kind info.

注释继续说我们可以通过使用 NativeDateTimeResolver 来更改它(尽管有一些限制)。

If you use NativeDateTimeResolver serialized native DateTime binary format and it can keep Kind 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.

Whosebug 上也有很多有用的信息比较 DateTime vs DateTimeOffset

这里解析器的顺序很重要。如果像这样在StandardResolver之前提供NativeDateTimeResolver,问题将得到解决。

.AddMessagePackProtocol(options =>
options.FormatterResolvers = new List<MessagePack.IFormatterResolver>()
{
    NativeDateTimeResolver.Instance,
    StandardResolver.Instance        
})