How to enforce a JSON serialization policy for EVERYWHERE in ASP.NET Core?

Viewed 365

I know that I can use this code to set a JSON policy in ASP.NET Core:

.AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
            options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        });

As you can see, I want the DictionaryKeyPolicy to be camelCased.

However, if I return a JsonResult, then this policy is not applied.

I know I can create a custom MyJsonResult to encapsulate this. But this means that I should make sure all of our developers use our custom JSON result.

I also know that I can create a helper class to return the policy object to me, but again this means that I should make sure all of our developers keep in mind to pass that object to JsonResult always.

However, the best way is to somehow apply this policy globally in a centralized place.

I want to know if it's possible to let ASP.NET Core understand that we want a global JSON serialization policy?

0 Answers
Related