Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core MVC dynamic return is not camelCased

Return a strongly typed object from your service, and it renders JSON properties as camelCase, because that's the default in ASP.NET Core MVC.

However, sometimes we need to create something on the fly using dynamic keyword and ExpandoObject class.

Those properties are not camelCased any more.

Howe to force ASP.NET Core MVC To cameCase everything?

like image 865
mohammad rostami siahgeli Avatar asked Oct 23 '25 15:10

mohammad rostami siahgeli


2 Answers

Within your Startup.cs you can specify a resolver to use for serialisation. The one you are looking for is CamelCasePropertyNamesContractResolver and it can be enabled with the following:

        services.AddMvc()
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
        });

I have tested it with a dynamic type and it is working as expected.

like image 123
Henry Avatar answered Oct 26 '25 07:10

Henry


On .NET 5 there is a specific flag to configure to serialize the dictionary keys

services.AddControllers()
                .AddJsonOptions(o =>
                    o.JsonSerializerOptions.DictionaryKeyPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
                );

More info
JsonSerializerOptions.DictionaryKeyPolicy Property
GitHub Issue

like image 31
Max Avatar answered Oct 26 '25 07:10

Max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!