How to set json serializer settings in asp.net core 3?

Alex Zaitsev picture Alex Zaitsev · Oct 15, 2019 · Viewed 71.7k times · Source

json serializer settings for legacy asp.net core applications were set by adding AddMvc().AddJsonOptions(), but I don't use AddMvc() in asp.net core 3. So how can I set global json serialization settings?

Answer

Kirk Larkin picture Kirk Larkin · Oct 15, 2019

AddMvc returns an IMvcBuilder implementation, which has a corresponding AddJsonOptions extension method. The new-style methods AddControllers, AddControllersWithViews, and AddRazorPages also return an IMvcBuilder implementation. Chain with these in the same way you would chain with AddMvc:

services.AddControllers()
    .AddJsonOptions(options =>
    {
        // ...
    });

Note that options here is no longer for Json.NET, but for the newer System.Text.Json APIs. If you still want to use Json.NET, see tymtam's answer