Pascalcase vs Camelcase in ASP.net Core

It’s not like the war of Pascalcase vs Camelcase hasn’t been going on for a very long time, but in ASP.net core it flared up again with a breaking change in ASP.net core 1.0. You can read the actual change request here on Github, and then the subsequent announcement with some unhappy campers here.

To be clear.

MyVariable <- PascalCase
myVariable <- camelCase

In earlier versions of Web API and indeed early versions of ASP.net core, the default serialization of an object to JSON results in Pascalcase names. When a C# app is talking to another C# app, the casing actually doesn’t matter. You can send JSON data with mYVaRiAbLE and it will still be deserialized into MyVariable in C#.

The issue usually reared it’s head when you were using javascript to consume your Web API. Afterall, when Mozilla, Google, jQuery, WordPress and countless others cite camelCase as the standard for Javascript naming, it’s probably what most people expect to see. If you are binding a model using Angular or similar from a Web API, you probably want to keep with the same naming format. Not have properties that came from your API suddenly be in Pascal Case.

It mostly comes down to the 80/20 rule. I would say a large majority of people using ASP.net core are also using some sort of javascript framework to bind models. And for that, camelCase is best.

So, what are your options if you are still #TeamPascalCase?

Change To PascalCase In ASP.net Core 1.0+

Probably the most annoying thing about this change is that you need to change the ContractResolver for the Json Serializer. The thing that gets people’s goat is that the resolver that makes things PascalCase is actually called the “DefaultContractResolver”…. Even though in version 1.0 and onwards it isn’t the default at all…..

In anycase, in your startup.cs file, find your ConfigureServices method. You should already have an AddMVC call, and tack onto it like so :

public void ConfigureServices(IServiceCollection services)
{
	services.AddMvc()
		.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}

Change To camelCase In ASP.net Core <1.0

Just incase you are behind with the times in ASP.net Core versions and you want to move to camelCase by default (Possibly in preparation for upgrading), you can do so by doing similar to the above, but instead making the contract resolver camel case like so :

public void ConfigureServices(IServiceCollection services)
{
	services.AddMvc()
		.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
}

Leave a Comment