I'm having quite some trouble with binding DateTimes in web api. Here is the situation. I have a controller that returns a model with a DateTime property. I've set up my web api to use IsoDateFormat and UTC time in the global.asax like this:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
The datetime format gets returned to the client in this format: 2013-02-04T11:24:48.91Z
Everything is working great on that side. But if i post it back in that same format the model binder doesnt recognize that property and leaves it null. What format do input datetimes need to be in order for the default DateTime model binding to work?
I have configured my Web API service the way you have specified, and I was able to post a DateTime of the format you have specified. Do you have [FromBody]
for your DateTime parameter? Primitive types are [FromUri]
by default.
public DateTime Post([FromBody]DateTime date)
{
return date;
}
Request:
POST http://localhost/api/values HTTP/1.1
content-type: application/json
Content-Length: 25
"2013-02-04T11:24:48.91Z"
Response:
HTTP/1.1 200 OK
Content-Length: 25
Content-Type: application/json; charset=utf-8
"2013-02-04T11:24:48.91Z"
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