Setting System.Text.Json serializer options globally in a asp.net core minimal web api
How to set the system.text.json serialization options globally.
As I am playing around with a .net core minimal web api for one of my side projects I needed to set some options to the System.Text.Json serializer globally so they would be applied to all requests/responses.
You can do this with the following code in your Program.cs
:
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.SerializerOptions.WriteIndented = true;
//... other options you might want to set.
});
I know this looks pretty straightforward, but when I was looking for how to do it I did not find that quick. I got the clue over at this github issue: https://github.com/dotnet/aspnetcore/issues/35904#issuecomment-908086822
UPDATE: I found the actual documentation on the Microsoft Learn website:
builder.Services.ConfigureHttpJsonOptions( options =>
{
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.SerializerOptions.WriteIndented = true;
});