【问题标题】:Adding new MediaType to NewtonsoftJsonInputFormatter doesn't work将新的 MediaType 添加到 NewtonsoftJsonInputFormatter 不起作用
【发布时间】:2021-12-08 10:48:20
【问题描述】:

我想为 .Net 5 中的MvcOptions 输入格式化程序添加一个新的 MediaType

当我执行以下操作时

services.AddControllers();

services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(options =>
{
    options.InputFormatters
 .OfType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>()
 .First()
 .SupportedMediaTypes
 .Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/csp-report"));
});

一切正常。但我想使用 Newtonsoft.Json 而不是默认的 Json-Serializer 所以我将代码更改为

services.AddControllers()
          .AddNewtonsoftJson();

services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(options =>
{
    options.InputFormatters
 .OfType<Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonInputFormatter>()
 .First()
 .SupportedMediaTypes
 .Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/csp-report"));
});

但现在每次将application/csp-report 发送到控制器时,我都会收到一个 415 状态代码。

【问题讨论】:

    标签: json.net .net-5 media-type inputformatter


    【解决方案1】:

    AddNewtonsoftJson 方法将添加两个输入格式化程序(NewtonsoftJsonInputFormatter 和 NewtonsoftJsonPatchInputFormatter),当您调用 OfType 时,两者都会返回,但是因为您选择的是第一个,所以它始终是 NewtonsoftJsonPatchInputFormatter,它最终被配置为您的新媒体键入不是您期望的 NewtonsoftJsonInputFormatter。

    所以作为一个可能的修复代码可能是这样的:

              .AddNewtonsoftJson();
    
    services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(options =>
    {
        options.InputFormatters
     .OfType<Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonInputFormatter>()
     .First(f => !(f is Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonPatchInputFormatter))
     .SupportedMediaTypes
     .Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/csp-report"));
    });
    

    所有信息都在这里:Adding new MediaType to NewtonsoftJsonInputFormatter doesn't work

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 2015-02-27
      • 2019-05-17
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多