asp.net-core.net-7.0json-serialization

ASP.NET Core 7 Web API - how to serialize in Pascal case?


In Visual Studio 2022, and .NET 7, I created a new project with the template ASP.NET Core Web API. The template creates the WeatherForeCastController, which uses the WeatherForecast model. The properties of the model are in PascalCase:

public class WeatherForecast
{
    public DateOnly Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    public string? Summary { get; set; }
}

When I execute the API from Swagger, I get the properties in camelCase:

[
  {
    "date": "2023-11-28",
    "temperatureC": 53,
    "temperatureF": 127,
    "summary": "Hot"
  },
...
]

But I want to get them as they are defined in the .NET class. I added the following two statements in Program.cs right after

builder.Services.AddSwaggerGen();

builder.Services.ConfigureHttpJsonOptions(
    options => options.SerializerOptions.PropertyNamingPolicy = null);
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(
    options => options.SerializerOptions.PropertyNamingPolicy = null);

But I still get the JSON properties in camelCase.

How can I get the JSON properties in exactly the same case as defined in the .NET class, in this case Pascal case?


Solution

  • Try to add it to AddControllers

    builder.Services.AddControllers()
    .AddJsonOptions(x =>
    {
        x.JsonSerializerOptions.PropertyNamingPolicy = null;
    });