gpt4 book ai didi

asp.net-web-api - Asp.net Web Api 将 UTC 时间字符串反序列化为本地时间

转载 作者:行者123 更新时间:2023-12-03 10:14:54 25 4
gpt4 key购买 nike

我有这个网址

http://example.com/api/record/getall?startdate=1994-11-05T17:15:30Z

和这个 webapi 端点

[ActionName("GetAll")]
public object GetAll(DateTime startDate)
{
...
}

我面临的问题是 startDate 接收反序列化的字符串作为本地时间,“ 11/5/1994 9:15:30 AM ” 而不是停留在我想要的 UTC 时间“ 11/5/1994 下午 5:15:30 "。

我正在使用 VS2012 update2,最新的 Json.net nuget 包。但是,如果我在单独的控制台应用程序中使用 json.net 进行测试,则相同的字符串“ 1994-11-05T17:15:30Z ” 能够正确反序列化为“ 11/5/1994 年下午 5:15:30 ”。

有人知道这里有什么问题吗?

最佳答案

虽然你已经found a solution对于您的问题,我想我会尝试解释为什么它没有按您的预期工作。

WebApi 使用内容类型协商来确定读取数据时使用的解析器。这意味着它将查看 Content-Type做出决定的请求的 header 。如果Content-Type header 设置为 application/json然后它将使用 Json.Net 解析内容并将其提供给您的方法。

HTTP GET 请求(例如您在此处发出的请求)没有设置内容类型。在这种情况下,“内容”实际上只是来自 URL 的查询字符串。 WebApi 不希望在这里找到 JSON 数据,因此它不会尝试使用 JSON 解析器来理解它。即使是这样,您传递给 GetAll 方法的字符串也不是有效的 JSON。 (它需要被引用才有效。)

现在,如果您要更改接受 POST 请求的方法,并将内容类型 header 设置为 application/json并将日期作为 JSON 字符串传递到正文中,然后 WebApi 将使用 Json.Net 来解析它,它会像您期望的那样工作。

例如,假设您的方法如下所示:

[HttpPost]
public object GetAll([FromBody]DateTime startDate)
{
try
{
return new
{
StartDate = startDate.ToString("yyyy-MM-dd HH:mm:ss"),
StartDateKind = startDate.Kind.ToString(),
};
}
catch (Exception ex)
{
return ex.Message;
}
}

你提出了这样的请求(注意 POST):
POST http://localhost:57524/api/values/GetAll HTTP/1.1
Content-Type: application/json
Content-Length: 22
Host: localhost:57524

"1994-11-05T17:15:30Z"

响应如下所示:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 31 May 2013 01:25:48 GMT
Content-Length: 57

{"StartDate":"1994-11-05 17:15:30","StartDateKind":"Utc"}

如您所见,在这种情况下,它确实将日期正确识别为 UTC。

关于asp.net-web-api - Asp.net Web Api 将 UTC 时间字符串反序列化为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16826093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com