ASP.NET Core 中的日期模型绑定 [英] Date model binding in ASP.NET Core

查看:30
本文介绍了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屋!

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