ASP.NET Core 6 Minimal API response JSON in camel case

685 views Asked by At

I want all JSON responses to use camel case, and tried below code, but it is not working and response is still in Pascal case. I also tried setting [JsonPropertyName("myCamelCaseProperty")] to override, but response still is in Pascal case.

Any suggestions how camel case can be made as default for all responses (all properties)?

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNameCaseInsensitive = false;
    options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});

builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();
2

There are 2 answers

1
AudioBubble On

By Default .Net 6 gives response in Camel Case. Here is the screen shot of my model and response.

Model

Response: Response

1
Selaka Nanayakkara On

In startup.cs :

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNameCaseInsensitive = false;
    options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});

builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

Then install Microsoft.AspNetCore.Mvc.NewtonsoftJson

<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.0" />

In you class reference above using [JsonProperty("customName")]

public class YourModel
{
    [JsonProperty("customName")]
    public string CustomName { get; set; }

    public string AnotherProperty { get; set; }
}