ASP.NET Core 3.0 中的 JsonOutputFormatter

JsonOutputFormatter in ASP.NET Core 3.0

在asp.net core 2.2中我曾经有过以下,

  var jsonSettings = new JsonSerializerSettings
  {
    ContractResolver = new SubstituteNullWithEmptyStringContractResolver()
  };

services.AddMvc(options =>
{
        options.OutputFormatters.RemoveType<JsonOutputFormatter>();
        options.OutputFormatters.Add(new ResponseJsonOutputFormatter(jsonSettings,ArrayPool<char>.Shared));
}

public class ResponseJsonOutputFormatter : JsonOutputFormatter
{
 // Stuff in here
}

但是在 3.0 中使用:

services.AddControllersWithViews(options =>

并且类型 JsonOutputFormatter 不再可用。

目前建议的全局自定义 json 响应的方法是什么?

我尝试使用 IOutputFormatter,但是当我在 AddControllersWithViews 中将它设置为 OutputFormatters 时它似乎没有连接,所以不确定是否有额外的步骤?

是否可以选择带有新端点路由的中间件?还是有更好的方法来实现这一目标?

我个人使用Json.NET

services.AddMvc().AddNewtonsoftJson();

Json.NET设置可以在调用AddNewtonsoftJson:

中设置
services.AddMvc()
    .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new CamelCasePropertyNamesContractResolver());

我在兼容模式下使用默认选项

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver =
             new DefaultContractResolver(); });

参考 Migrate from ASP.Net 2.2 to 3.0

要恢复到 NewtonsoftJson 并配置其输出格式化程序,首先添加对 Microsoft.AspNetCore.Mvc.NewtonsoftJson 的包引用,然后在 ConfigureServices 中,您需要在调用 之后调用 AddControllerAddNewtonsoftJson:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
            .AddNewtonsoftJson();
    
    services.Configure<MvcOptions>(options =>
        {
            NewtonsoftJsonOutputFormatter jsonOutputFormatter = options.OutputFormatters.OfType<NewtonsoftJsonOutputFormatter>().Single();
        
            // makes changes to the Newtonsoft JSON Output Formatter here.
        });
}