首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NewtonsoftJsonInputFormatter在.NET5中不能作为InputFormatter使用

NewtonsoftJsonInputFormatter在.NET5中不能作为InputFormatter使用
EN

Stack Overflow用户
提问于 2021-05-04 09:49:03
回答 1查看 100关注 0票数 0

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

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

代码语言:javascript
复制
  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();
    })
}
EN

回答 1

Stack Overflow用户

发布于 2021-05-04 11:17:50

基于帖子here。那篇文章中被接受的答案对我不起作用。然而,另一个由@Vincent Rutten提出的建议工作确实有效

代码语言:javascript
复制
 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);
                  });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67377799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档