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 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. AddJsonOptions configures Microsoft.AspNetCore.Http.Json.JsonOptions using the Dependency Injection (source). So, you can do the same directly. In the following example, I configure the JSON serializer options using the Configure method:

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?Buy Me A Coffee💖 Sponsor on GitHub