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

查看:428
本文介绍了将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 AM

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:
我注意到,当我POST 2014-04-01T00:00:00Z 它将在C#中序列化为UTC DateTime类。然而,我发现一些工作是在 endDate.Value.ToUniversalTime()之间进行转换,尽管我发现它对于POST而不是一个GET来说是奇怪的。 / p>

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使用模型绑定绑定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 ,它使用该设置,并获得所需的日期时间。 BTW,如果将此设置更改为 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天全站免登陆