Web API - Culture Specific Date Time Formatting

Model binding in Web API doesn't work like it does in MVC. Whenever I pass in a different date time format (DD/MM/YYYY) to the web api via a POST method, API model formatter doesn't know how to parse it.

So, how can i fix it?

I have a model like this.

public class Item{
  public int ID {get;set;}
  public DateTime LastModified {get;set;}
}

And I'm using this in my API like this.

public HttpResponseMessage Post(int warehouseId, Item model)
{
  // magic
}

passed the JSON object via JS would be something like this:

{
  "ID": 1,
  "LastModified" : "23/12/2014"
}

Web API doesn't know how to parse this date format (UK , en-GB). To fix this using a model binder doesn't work. Instead, we have to use a converter. in this case a Json Converter. Lucky for us, there is already an attribute called JsonConverter which we can use. But we need to specify our custom formatter here.

public class Item{
    public int ID {get;set;} 

    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime LastModified {get;set;}
}

now we have to specify out custom format in the CustomDateTimeConverter class

class CustomDateTimeConverter : IsoDateTimeConverter
{
    public CustomDateTimeConverter()
    {
        base.DateTimeFormat = "yyyy-MM-dd";
    }
}
Refs:
http://stackoverflow.com/a/18639829/959245

Popular posts from this blog

Print a receipt using a Thermal Printer with C#.NET

Automatic redirect upon session timeout using ASP.NET MVC and Javascript

Complex Master-Detail Form using Knockout.js and ASP.NET MVC