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!

9 thoughts on “Going camelCase in ASP.NET MVC Web API

    • I prefer to name it “Crc32” so it would become “crc32”. Unfortunately the older .NET base class libraries are inconsistent with 2-letter acronyms (‘DB’ vs. ‘Db’) and it is also inconsistent with the JavaScript naming conventions I know. E.g. “MyCrc32” would become “myCrc32” and it should be “myCRC32”. I suppose you could have some manual override but I’m not sure if it’s worth the trouble.

      Like

  1. Great Solution . But the problem it is working only for the root level element properties , child object properties are still in pascal case. Any generic solutions are highly appreciated

    Like

Leave a comment