将 UTC DateTime 传递给 Web API HttpGet 方法导致本地时间 [英] Passing UTC DateTime to Web API HttpGet Method results in local time

查看:21
本文介绍了将 UTC DateTime 传递给 Web API HttpGet 方法导致本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 UTC 日期作为查询字符串参数传递给 Web API 方法.网址看起来像

I'm trying to pass a UTC date as a query string parameter to a Web API method. The URL looks like

/api/order?endDate=2014-04-01T00:00:00Z&zoneId=4

方法的签名看起来像

[HttpGet]
public object Index(int zoneId, DateTime? endDate = null)

日期是 31/03/2014 8:00:00 PM 但我希望它是 01/04/2014 12:00:00上午

The date is coming in as 31/03/2014 8:00:00 PM but I'd like it to come in as 01/04/2014 12:00:00 AM

我的 JsonFormatter.SerializerSettings 看起来像这样

new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    DateTimeZoneHandling = DateTimeZoneHandling.Utc,
    DateFormatHandling = DateFormatHandling.IsoDateFormat
};

编辑#1:我注意到当我发布 2014-04-01T00:00:00Z 时,它将序列化为 C# 中的 UTC DateTime 类型.但是,我找到了一种解决方法,可以使用 endDate.Value.ToUniversalTime() 来转换它,尽管我发现它对 POST 而不是 GET 的工作方式很奇怪.

EDIT #1: I've noticed when I POST 2014-04-01T00:00:00Z it will serialize to the UTC DateTime kind in C#. However I've found a work around of doing endDate.Value.ToUniversalTime() to convert it although I find it odd how it works for a POST but not a GET.

推荐答案

您发送的查询字符串参数值 2014-04-01T00:00:00Z 是 UTC 时间.因此,相同的时间会根据您的本地时钟转换为时间,如果您调用 ToUniversalTime(),它会转换回 UTC.

The query string parameter value you are sending 2014-04-01T00:00:00Z is UTC time. So, the same gets translated to a time based on your local clock and if you call ToUniversalTime(), it gets converted back to UTC.

那么,问题究竟是什么?如果问题是如果作为查询字符串发送而不是在请求正文中发布时为什么会发生这种情况,那么该问题的答案是 ASP.NET Web API 使用 model binding<绑定 URI 路径、查询字符串等/em> 和主体使用参数绑定.对于后者,它使用媒体格式化程序.如果您发送 JSON,则使用 JSON 媒体格式化程序,它基于 JSON.NET.

So, what exactly is the question? If the question is why is this happening if sent in as query string but not when posted in request body, the answer to that question is that ASP.NET Web API binds the URI path, query string, etc using model binding and the body using parameter binding. For latter, it uses a media formatter. If you send JSON, the JSON media formatter is used and it is based on JSON.NET.

由于您已指定 DateTimeZoneHandling.Utc,它使用该设置并获得您想要的日期时间类型.顺便说一句,如果您将此设置更改为 DateTimeZoneHandling.Local,那么您将看到与模型绑定相同的行为.

Since you have specified DateTimeZoneHandling.Utc, it uses that setting and you get the date time kind you want. BTW, if you change this setting to DateTimeZoneHandling.Local, then you will see the same behavior as model binding.

这篇关于将 UTC DateTime 传递给 Web API HttpGet 方法导致本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆