c# - QueryString 与 Body 中的 ASP.NET DateTime 序列化

标签 c# asp.net-core

我注意到 DateTime 对象在 QueryString 和 Body 之间针对相同的值进行了不同的序列化。基础值仍然是相同的正确值,但是序列化的 QueryString 的 DateTimeKindLocal,而 Body 为 Utc

端点

[HttpPost]
public ActionResult Post([FromQuery] DateTime queryDate, [FromBody] DateTime bodyDate)
{
  var result = new
  {
    queryDateKind = queryDate.Kind.ToString(),
    bodyDateKind = bodyDate.Kind.ToString()
  };

  return new ObjectResult(result);
}

请求

POST /api/values?queryDate=2019-05-12T00%3A00%3A00.000Z HTTP/1.1
Host: localhost:5000
Content-Type: application/json
cache-control: no-cache
"2019-05-12T00:00:00.000Z"

响应

{
    "queryDateKind": "Local",
    "bodyDateKind": "Utc"
}

知道这是为什么吗?是否有一个设置总是序列化为相同的 DateTimeKind

最好我不想在任何地方都使用 ToUniversalTime()ToLocalTime(),也不想使用任何自定义的 IModelBinder

最佳答案

不幸的是,事情就是这样,看看这个答案 - Passing UTC DateTime to Web API HttpGet Method results in local time

这与如何区别对待查询字符串参数和消息体、模型绑定(bind)与参数绑定(bind)有关。

您将不得不调用 .ToUniversalTime() 或实现您自己的模型绑定(bind)器来解决这个问题。

关于c# - QueryString 与 Body 中的 ASP.NET DateTime 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56113032/

相关文章:

c# - 是否可以使用相关状态对象在消息检查器中传递 channel 数据?

asp.net-core - 使用 ASP.NET 5 Cookie 身份验证的 Context.Response.SignIn() 的命名空间是什么

c# - 我如何判断给定的 hWnd 是否仍然有效?

c# - 如何从 WCF 服务响应中删除 outerXML

c# - 查看详细信息窗口不会展开集合属性

logging - Serilog 接收器到 ASPNET Core 日志记录

c# - IdentityServer4在asp.net core中注册UserService并从数据库中获取用户

c# - Entity Framework IdentityUser覆盖用户名不会保存在数据库中

javascript - 为什么从模型获取值时我的引导日期选择器日历不更新?

c# - 仅在任务 RanToCompletion 上使用 SynchronizationContext