I'm building one ASP.NET Core Web API and I've recently found one issue regarding the binding of DateTime values.
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");
so I doubt this to be the reason.
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?
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:
That should take care of proper model binding in your case.