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
.
[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);
}
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"
{
"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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With