Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API format datetime differently between two APIs in the same Web app

I am using the normal way to configure Web APIs in my project, however, I do have a legacy API which I need to support.

I configure the datetime format like this:

JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        jsonFormatter.SerializerSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Include,
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        var converters = jsonFormatter.SerializerSettings.Converters;
        converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss" });

This is exactly what I want for most of the API controllers, however, with the legacy API, it needs to output DateTimes using the old MS AJAX format, like this:

/Date(1345302000000)/

So anyone know how I can specify a different JSON date formatter for one of my API modules and leave the Global Configuration as-is? OR any alternative, such as a config per API would be fine. thanks

like image 948
krisdyson Avatar asked Aug 18 '12 13:08

krisdyson


1 Answers

Web API has a concept called Per-Controller configuration just for scenarios like yours. Per-controller configuration enables you to have configuration on a per-controller basis.

public class MyConfigAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
    {
        // controllerSettings.Formatters is a cloned list of formatters that are present on the GlobalConfiguration
        // Note that the formatters are not cloned themselves
        controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter);

        //Add your Json formatter with the datetime settings that you need here
        controllerSettings.Formatters.Insert(0, **your json formatter with datetime settings**);
    }
}

[MyConfig]
public class ValuesController : ApiController
{
    public string Get(int id)
    {
        return "value";
    }
}

In the above example, ValuesController would be using the Json formatter with your date time settings, but rest of the controllers in your would be using the one on GlobalConfiguration.

like image 63
Kiran Avatar answered Sep 21 '22 19:09

Kiran