Configuring JSON options in ASP.NET Core

 
 
  • Gérald Barré

In an ASP.NET Core application, you can configure the JSON serializer options used by controllers using the AddJsonOptions method:

C#
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
            .AddJsonOptions(options =>
               options.JsonSerializerOptions.PropertyNamingPolicy = null);
}

This works well for controllers. .NET 6 introduced minimal APIs, a simpler model for building lightweight web APIs without controllers. Because minimal APIs do not use controllers, the AddJsonOptions method is not available. However, minimal APIs rely on Microsoft.AspNetCore.Http.Json.JsonOptions configured through Dependency Injection (source). You can configure it directly using the Configure method, as shown below:

C#
var builder = WebApplication.CreateBuilder(args);

// Set the JSON serializer options
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNameCaseInsensitive = false;
    options.SerializerOptions.PropertyNamingPolicy = null;
    options.SerializerOptions.WriteIndented = true;
});

var app = builder.Build();
app.MapGet("/", () => new { FirstName = "Gérald", LastName = "Barré" });
app.Run();

The JSON serializer uses the configuration settingsThe JSON serializer uses the configuration settings

In .NET 6 preview 7, you can also provide the JSON serializer options using Results.Json(object, JsonSerializerOptions) (source):

C#
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
    WriteIndented = true,
};

app.MapGet("/", () => Results.Json(new { FirstName = "Gérald", LastName = "Barré" }, options));

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?