ASP.NET Core MVC JSON Output in camelCase or PascalCase

JSONYou may have noticed if you have migrated from ASP.NET Web API to ASP.NET Core, that the default case for serializing output to JSON is now camelCase.

If you want to see the history, you can check out this issue on the ASP.NET Core MVC GitHub.

Pascal Default

As mentioned, the default is now camelCase.  If you need/want all of the JSON output to be in PascalCase, then the solution is pretty simple.

All you need to do is specify the DefaultContractResolver.

Profile

Another option, which I chose to use, is to specify an accept header of application/json but with an profile.

Darrel Miller pointed this out to me a couple years ago.

Profiles are defined in section 3 of RFC6906:

The concept of a profile has no strict definition on the Internet or
on the web. For the purpose of this specification, a profile can be
described as additional semantics that can be used to process a
resource representation, such as constraints, conventions,
extensions, or any other aspects that do not alter the basic media
type semantics.

What this could look like for us is defining the accept header of our request as:

Accept: application/json;profile="https://en.wikipedia.org/wiki/PascalCase"

Output Formatter

One of the ways I found to implement this in ASP.NET Core MVC is with an Output Formatter.

What we can do is define a new custom output formatter that will be used when the request accepts application/json;profile="https://en.wikipedia.org/wiki/PascalCase".

Now to use this new output formatter, we must specify in our ConfigureServices.

Output

Here is a request with the profile defined in the accept header to return PascalCase.

JSON PascalCase

Then another request without the profile, which is just a standard application/json, which by default is camelCase.
JSON camelCase

More

This is one specific use case of using a custom output formatter.  There are likely many different situations you may run into where it might be a good fit to create one.

Have you written a custom output formatter?  If so, I’d love to hear about it in the comments or on Twitter.