audir
audir

Reputation: 1

.Net WebApi 1 datetime converter

i have a webapi 1.0 inside mvc 4.0.

There's a way to change (globally) the default converter for a datetime field for webapi request for content-type x-www-form-urlencoded?

The field that the client sent to the server is in this format dd/mm/yyyy but the server seems to convert only date in this format mm/dd/yyyy

This is the curl request

curl "http://xxxx/yyy/apimethod/" 
-H "Accept-Encoding: gzip, deflate" 
-H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" 
--data "ExpiryDate=30%2F04%2F2015&UserId=32" 

This is the method

[HttpPost]
public HttpResponseMessage apimethod(MyModel model) {}

and this is the model

public class MyModel{

      public int UserId { get; set; }

      [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]            
      public DateTime ExpiryDate { get; set; }
}

Upvotes: 0

Views: 1887

Answers (1)

Andrii Tsok
Andrii Tsok

Reputation: 1446

In ASP.NET Web API, you can add different Json.NET DateTimeConverters through the JsonFormatter's SerializerSettings to make your Serializer use different DateTime format.

public class MyDateTimeConvertor : DateTimeConverterBase
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return DateTime.ParseExact(reader.Value.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue( ((DateTime)value).ToString("dd/MM/yyyy") );
    }
}

And then add this converter to serialization settings:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateTimeConvertor());

Upvotes: 1

Related Questions