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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With