【问题标题】:JsonOutputFormatter in ASP.NET Core 3.0ASP.NET Core 3.0 中的 JsonOutputFormatter
【发布时间】:2020-03-23 17:18:23
【问题描述】:

在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 时,它似乎没有连接,所以不确定是否有额外的步骤?

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

【问题讨论】:

标签: c# json asp.net-core-3.0


【解决方案1】:

我个人使用 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

【讨论】:

  • 如果您正在做的是将输出重写为不同的结构,这将不起作用。它只处理格式外观的选项。
  • 好的...但是,我该如何全局添加它呢? --(即 OData 不会使用它;并且没有名为 AddNewtonsoftJson 的扩展方法可以添加到 services.AddOData() 调用中。)
【解决方案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.
        });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2020-02-03
    相关资源
    最近更新 更多