4

I'm using web API help documentation to connect API devs and UI client devs. One of the item I would like to define in the help is the Date format. And want it to be customized within the sample of request/response information at the API action details page:

I have request entity:

public class Request
{
    public string Id {get;set;}
    public string Type {get;set;}
    public DateTime Date {get;set;} 
}

This is a default representation at the help page:

{
  "Id": "sample string 1",
  "Type": "sample string 2",
  "Date": "2014-08-12T19:33:09.6221727+00:00"
}

I want it to be like the following:

{
  "Id": "sample string 1",
  "Type": "sample string 2",
  "Date": "08/13/2014"
}

How can I achieve this goal?

Mando
  • 11,414
  • 17
  • 86
  • 167

1 Answers1

3

It turned out that ASP.NET Web.API uses the common Json.NET formatter and you can register your own date converter for this purposes:

   public class MyDateFormatConverter : DateTimeConverterBase
    {
        public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            return DateTime.Parse(reader.Value.ToString());
        }

        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            writer.WriteValue(((DateTime)value).ToString("d"));
        }
    }

and then register it at the GLOBAL (WebApiConfig, not HelpPageConfig) config:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateFormatConverter());
Mando
  • 11,414
  • 17
  • 86
  • 167