Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp web api DateTime model binding

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?

like image 597
Dennis Puzak Avatar asked Oct 21 '22 18:10

Dennis Puzak


1 Answers

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"
like image 67
Maggie Ying Avatar answered Dec 17 '22 23:12

Maggie Ying