如何在 asp.net core 3 中设置 json 序列化器设置?

问题描述:

遗留asp.net 核心应用程序的json 序列化器设置是通过添加AddMvc().AddJsonOptions() 设置的,但我没有在AddMvc() 中使用AddMvc()代码>asp.net core 3.那么如何设置全局json序列化设置呢?

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?

AddMvc 返回一个 IMvcBuilder 实现,有对应的AddJsonOptions 扩展方法.新式方法AddControllersAddControllersWithViewsAddRazorPages 也返回一个IMvcBuilder 实现.以与链接 AddMvc 相同的方式链接这些:

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 =>
    {
        // ...
    });

请注意,这里的 options 不再适用于 Json.NET,而是适用于较新的 System.Text.Json API.如果您仍想使用 Json.NET,请参阅 tymtam 的回答

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