ASP.NET Core 3.0中的JsonOutputFormatter

12
在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替代品[tag:System.Text.Json]目前没有公共的等价物来替代Json.NET的contract resolver。因此,建议您继续使用Json.NET。 - dbc
2
备选方案是 NewtonsoftJsonOutputFormatter - tchelidze
2个回答

11

我个人使用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(); });

参考 从ASP.Net 2.2迁移到3.0


5
如果你正在将输出重写为不同的结构,那么这种方法就不起作用了。它只涉及格式外观的选项。 - James Hancock
好的...但是,我怎么才能将它全局添加呢?(即OData不会使用它;也没有名为AddNewtonsoftJson的扩展方法可以添加到services.AddOData()调用中。) - BrainSlugs83

2

要切换回NewtonsoftJson并配置其输出格式,首先添加对Microsoft.AspNetCore.Mvc.NewtonsoftJson的包引用,然后在ConfigureServices中,在调用AddControllerAddNewtonsoftJson之后需要调用Configure:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接