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:

public void ConfigureServices(IServiceCollection services)
            .AddJsonOptions(options =>
               options.JsonSerializerOptions.PropertyNamingPolicy = null);

This works well for controllers. .NET 6 introduced minimal APIs for hosting and routing in web applications. This is an easier way to create small web APIs. This new model does not use controllers, so you cannot use the AddJsonOptions method. Instead, you should configure the JsonOptions directly. Note that this is exactly what AddJsonOptions does under the hood (source).

using Microsoft.AspNetCore.Http.Json;

var builder = WebApplication.CreateBuilder(args);

// Set the JSON serializer options
builder.Services.Configure<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é" });

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):

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?Buy Me A Coffee