2

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?

1
  • This SO stackoverflow.com/questions/16826093/… has a longer explanation why it behaves this way and that JSON.net is not involved here. Another answer in the same post provides a solution for asp.net (not core!) using a custom IModelBinder. I am sure there is a similar possibility in asp.net core. Commented Aug 11, 2017 at 18:44

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This does work when the date is bound FromBody which is JSON. But not when the query string is bound, as in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.