【问题标题】:NewtonsoftJsonInputFormatter is not available as InputFormatter in .NET5NewtonsoftJsonInputFormatter 在 .NET5 中不能用作 InputFormatter
【发布时间】:2021-05-04 01:49:02
【问题描述】:

我有 NET5 应用程序,在启动时我已将应用程序配置为使用 Newtonsoft 而不是 System.Text.Json. 对于发布 CSP 报告,我想添加 application/csp-report 作为支持的媒体类型。

即使我已经使用AddNewtonsoftJson 配置为使用Newtonsoft,NewtonsoftJsonInputFormatter 仍然不能用作输入格式化程序。以下代码返回 null 当尝试在 InputFormatters 集合中查找时。

  public void ConfigureServices(IServiceCollection services)
  {   
    services.AddControllersWithViews(config =>
    {
        var jsonInputFormatter = options.InputFormatters
           .OfType<NewtonsoftJsonInputFormatter>()
           .First();
         
         //jsonInputFormatter  is null here
         
        jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report")
    })
    // Use Newtonsoft’s Json.NET instead of System.Text.Json.
    .AddNewtonsoftJson((options)=> 
    {
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    })
}

【问题讨论】:

    标签: asp.net-core .net-core asp.net-core-mvc .net-5


    【解决方案1】:

    基于帖子 here 。该帖子中接受的答案对我不起作用。然而,@Vincent Rutten 提出的其他建议解决方法确实有效

     services.AddOptions<MvcOptions>()
                  .PostConfigure<IOptions<JsonOptions>, IOptions<MvcNewtonsoftJsonOptions>, ArrayPool<char>, ObjectPoolProvider, ILoggerFactory>(
                      (mvcOptions, jsonOpts, newtonJsonOpts, charPool, objectPoolProvider, loggerFactory) =>
                      {
                          var formatter = mvcOptions.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().First(i => i.SupportedMediaTypes.Contains("application/json"));
                          formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/csp-report"));
                          mvcOptions.InputFormatters.RemoveType<NewtonsoftJsonInputFormatter>();
                          mvcOptions.InputFormatters.Add(formatter);
                      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      相关资源
      最近更新 更多