Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET DateTime Serialization in QueryString vs Body

I noticed DateTime objects are serialized differently for the same values between QueryString and Body. The underlying value is still the same correct value, however the serialized QueryString has a DateTimeKind of Local, whereas the Body is Utc.

Endpoint

[HttpPost]
public ActionResult Post([FromQuery] DateTime queryDate, [FromBody] DateTime bodyDate)
{
  var result = new
  {
    queryDateKind = queryDate.Kind.ToString(),
    bodyDateKind = bodyDate.Kind.ToString()
  };

  return new ObjectResult(result);
}

Request

POST /api/values?queryDate=2019-05-12T00%3A00%3A00.000Z HTTP/1.1
Host: localhost:5000
Content-Type: application/json
cache-control: no-cache
"2019-05-12T00:00:00.000Z"

Response

{
    "queryDateKind": "Local",
    "bodyDateKind": "Utc"
}

Any idea why this is? Is there perhaps a setting to always serialize to the same DateTimeKind?

Preferably I wouldn't want to use ToUniversalTime() or ToLocalTime() everywhere, nor use any custom IModelBinder.

like image 612
JvR Avatar asked May 13 '19 13:05

JvR


1 Answers

Unfortunately that's the way it is, have a look at this answer - Passing UTC DateTime to Web API HttpGet Method results in local time

It's related to how query string parameters and message bodies are treated differently, Model binding vs parameter binding.

You will have to either call .ToUniversalTime() or implement your own model binder to get around this.

like image 53
Janus Pienaar Avatar answered Sep 17 '22 13:09

Janus Pienaar