asp.net-core - 避免 DateTime 转换,同时将其传递给 AspNetCore.SignalR .Net 客户端

标签 asp.net-core signalr signalr.client asp.net-core-signalr msgpack

我正在尝试将请求从服务器发送到在特定文化环境中运行的客户端(.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 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.

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

关于asp.net-core - 避免 DateTime 转换,同时将其传递给 AspNetCore.SignalR .Net 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52781568/

相关文章:

c# - 找不到任何已安装的.NET Core SDK

c# - Asp.net Core 中的 HttpContext 异步安全吗?

c# - 如何在 ASP.NET Core 应用程序中使用位图资源?

javascript - SignalR 从服务器返回字符串到客户端

c# - 核心 2.1 signalR 成功连接但客户端为空

.net-core - SignalR Core Hub 与 BackgroundService .NET Core 交互

asp.net-web-api - 在 ASP.NET Core RC2 中使用 HttpConfiguration

asp.net-mvc-4 - 如何在SignalR(.NET客户端)中使用自定义基本身份验证?

SignalR "Error during negotiation request"

signalr - 如何使用SignalR的往返状态?