ASP.NET Core中的日期模型绑定 [英] Date model binding in ASP.NET Core
问题描述
我正在构建一个ASP.NET Core Web API,最近发现了一个有关DateTime值绑定的问题.
I'm building one ASP.NET Core Web API and I've recently found one issue regarding the binding of DateTime values.
实际上,我具有一个minimumDate
和一个maximumDate
属性,用于在特定资源中进行过滤.这些是一个Filtering
对象的一部分,该对象只是通过模型绑定填充到控制器上.
In truth I have one minimumDate
and one maximumDate
properties for filtering in a certain resource. These are part of one Filtering
object which just gets populated on the controller by model binding.
问题在于请求是这样发送的:
The issue is that the request is sent like this:
minimumDate=2014-01-20T00:00:00.000Z&maximumDate=2014-03-21T00:00:00.000Z
并在控制器上进行调试时得到:
and on the controller one gets when debuging:
MinimumDate = 19/01/2014 22:00:00
MaximumDate = 20/03/2014 21:00:00
这显然是错误的.预期是:
This is clearly wrong. The expected was:
MinimumDate = 20/01/2014 00:00:00
MaximumDate = 21/03/2014 00:00:00
它在最小日期和最大日期中都减少了一天,而且还弄乱了时间部分.
It is reducing one day in both the minimum and maximum dates and furthermore it is messing the time part.
我认为起初它与文化和全球化有关,但这已在启动"配置方法中设置为:
I thought at first it had to do with culture and globalization, but this is already set in the Startup configure method as:
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-BR");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("pt-BR");
所以我怀疑这是原因.
我做错了什么?如何通过模型绑定将日期正确发送到API?
What am I doing wrong? How to get dates properly being sent to the API with model binding?
编辑,我通过使用以下方法手动解析日期时间对象来解决了该问题:
EDIT I managed to solve the issue by manualy parsing the datetime objects using:
filtering.MinimumDate = DateTime.Parse(this.Request.Query["minimumDate"], null, System.Globalization.DateTimeStyles.RoundtripKind);
filtering.MaximumDate = DateTime.Parse(this.Request.Query["maximumDate"], null, System.Globalization.DateTimeStyles.RoundtripKind);
换句话说,绕过模型联编程序.我仍然想知道:为什么模型绑定在这里呈现这种奇怪的行为?
In other words, bypassing the model binder. Still, I want to know: why model binding is presenting this strange behavior here?
推荐答案
在我看来,在后台使用Json.net的模型活页夹正在将UTC时间转换为BRT(UTC-3)的本地时间,即为什么您看到日期和时间更改.您应该能够将您的JsonSerializerSettings属性更新为:
To me it looks like the model binder which uses Json.net behind the scenes is converting your UTC time to local time for BRT (UTC-3) which is why you see the date and time change. You should be able to update your JsonSerializerSettings property as:
new JsonSerializerSettings
{
.....
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
.....
}
在您的情况下,应该注意适当的模型绑定.
That should take care of proper model binding in your case.
这篇关于ASP.NET Core中的日期模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!