I\'m trying to return camel cased JSON from an ASP.Net Web API 2 controller. I created a new web application with just the ASP.Net MVC and Web API bits in it. I hijacked t
I was using Owin and DI (AutoFac in my case) so that throws another wrench into the works. My Startup.cs contains:
var apiconfig = new HttpConfiguration
{
DependencyResolver = new AutofacWebApiDependencyResolver(container)
};
WebApiConfig.Register(apiconfig);
Then in my WebApiConfig.cs I have:
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Setup json.Net for pretty output, easy human reading AND this formatter
// does that ONLY for browsers - best of both worlds: useful AND efficient/performant!
config.Formatters.Clear();
config.Formatters.Add(new BrowserJsonFormatter());
}
public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
// Since most browser defaults do not include an "accept type" specifying json, this provides a work around
// Default to json over XML - any app that wants XML can ask specifically for it ;)
public BrowserJsonFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
SerializerSettings.Formatting = Formatting.Indented;
SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Convert all dates to UTC
SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
}
// Change the return type to json, as most browsers will format correctly with type as text/html
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
headers.ContentType = new MediaTypeHeaderValue("application/json");
}
}