Going camelCase in ASP.NET MVC Web API

With Web API it’s super easy to return JSON from the server by returning .NET objects. Unfortunately in .NET public properties are PascalCased while in JavaScript properties are camelCased.

I’ve seen several solutions for prerelease versions of the Web API requiring a few pages of code to override the default behavior. I’ve just found a super easy way that I’d like to share with you. In the default template of an ASP.NET MVC Web API project insert this in your RouteConfig.RegisterRoutes or WebApiConfig.Register, whichever receives GlobalConfiguration.Configuration:

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

Oh, and don’t forget to add using Newtonsoft.Json.Serialization; to your using statements.

Hope this helps!