Search code examples
c#asp.net-corecamelcasing

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?


Solution

  • 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.