0

我想MvcOptions在 .Net 5 的输入格式化程序中添加一个新的 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"));
});

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

4

1 回答 1

0

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

此处的所有信息:将新 MediaType 添加到 NewtonsoftJsonInputFormatter 不起作用

于 2021-12-10T07:33:03.707 回答