我的问题与此类似:Asp.net WebApi deserializes UTC time string to local time
除了我在我的 Controller 方法中使用 ([FromBody] dtoWithTime)
Controller 调用看起来像
public JsonResult DiscoverProject([FromBody] dtoWithTime dto) {}
在哪里(我已经简化了这个例子使用。)
[Serializable]
public class dtoWithTime
{
public DateTime? dateName { get; set; }
}
请求以带有这些 header /数据的 POST 形式传入(取自 fiddler)
accept: application/json
content-type: application/json
content-length: 281
Connection: keep-alive
{"dateName":"2014-05-31T00:00:00.000Z"}
当日期进入 Controller 时,它变成 2014-05-30 20:00:00
我希望日期以 Utc 类型从 UI 发送过来。我能够在 Controller 中使用 ToUniversalTime() 操作日期,这可以按我想要的方式工作,但检查此日期的 SpecFlow 测试失败。如果我能让序列化程序保持 Utc 时间,一切都会很好。
我尝试使用的是 JsonDotNetValueProviderFactory并在 global.asax.cs 中设置默认设置
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
这对我有用,但破坏了我们应用程序中的许多序列化,包括枚举。
那么有没有办法装饰 DateTime?或者为 MVC json 反序列化器设置默认日期类型?
最佳答案
JSON 是传输数据的绝佳格式。不幸的是,它做得不好的一件事是日期。有许多解决方法可以让它们在不同平台上正常工作。最终我们最终做的是将所有 JSON 日期数据作为字符串发送。然后在我们的 Controller 中,我们使用 TryParse 将它们转换为真正的 DateTime 类型:
DateTime myDate
if (DateTime.TryParse(inputJsonStringDate, out myDate))
//Success
else
//Not a valid date
关于c# - 将 UTC 时间字符串反序列化为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23920761/