CamelCase not working in net core 6 web api

Viewed 2589

I've migrated a web api application from net core 5 to 6 and changed NewtonSoft serializer by System.Text.Json. In my Startup.cs, I've configured Json serialization with the following code:

services.AddControllers(config =>
{
    config.RespectBrowserAcceptHeader = true;
    config.ReturnHttpNotAcceptable = true;
})
.AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    options.JsonSerializerOptions.WriteIndented = true;
})
.AddXmlDataContractSerializerFormatters();

This code is working only partially. WriteIndented is working fine (see screen capture below), but I can't get camelcase to work.

enter image description here

Any suggestions? Regards

3 Answers

After many tries I solved this problem. In latest version there is no default issue with "BaseController" but same issue with "ODataController".

The solution is;

services
.AddControllers(opt => opt.Filters.Add(typeof(ValidateModelAttribute)))
.AddJsonOptions(o => {
   o.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
   o.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
   o.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
   o.JsonSerializerOptions.WriteIndented = true;
})
.AddOData(options => options.Select().Expand().Filter().OrderBy().SetMaxTop(32).Count());

Read more detail on this documents.

Simply add this in the program.cs file

using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
JsonConvert.DefaultSettings = () =>
 {
   var settings = new JsonSerializerSettings();
   settings.Converters.Add(new StringEnumConverter());
   settings.ContractResolver = new 
   CamelCasePropertyNamesContractResolver();
   return settings;
 };

please try this way: Add option UseCamelCasing in NewtonsoftJson.

services.AddControllers()
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    options.UseCamelCasing(true); // additional line here
                });
Related