c# - ASP.NET Core 中的内容类型 "415 Unsupported Media Type"为 "application/csp-report"

标签 c# asp.net-core asp.net-core-3.1

我的内容安全政策导致 Chrome 发布报告,但接收报告的操作返回“415 不支持的媒体类型”。我理解这是因为该帖子的内容类型为“application/csp-report”。如何将其添加为 Core 3.1 中允许的内容类型(基本上只是 json)。

行动

// https://anthonychu.ca/post/aspnet-core-csp/
[HttpPost][Consumes("application/csp-report")]
public IActionResult Report([FromBody] CspReportRequest request)
{
    return Ok();
}

模型缩小版

public class CspReportRequest
{
    [JsonProperty(PropertyName = "csp-report")]
    public CspReport CspReport { get; set; }
}

public class CspReport
{
    [JsonProperty(PropertyName = "document-uri")]
    public string DocumentUri { get; set; }
}

最佳答案

以下示例演示如何添加对 SystemTextJsonInputFormatter 的支持用于处理其他媒体类型:

services.AddControllers(options =>
{
    var jsonInputFormatter = options.InputFormatters
        .OfType<SystemTextJsonInputFormatter>()
        .Single();

    jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report");
});

这是一个两步过程:

  1. 询问已配置的输入格式化程序列表以查找 SystemTextJsonInputFormatter .
  2. 添加application/csp-report添加到其现有的受支持媒体类型列表( application/jsontext/jsonapplication/*+json )。
<小时/>

如果您使用 Json.NET 而不是 System.Text.Json ,方法类似:

services.AddControllers(options =>
{
    var jsonInputFormatter = options.InputFormatters
        .OfType<NewtonsoftJsonInputFormatter>()
        .First();

    jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report");
})

有两个小差异:

  1. 类型为NewtonsoftJsonInputFormatter而不是SystemTextJsonInputFormatter .
  2. 集合中有两个此类型的实例,因此我们定位第一个(有关具体信息,请参阅 this answer)。
<小时/>

参见Input Formatters在 ASP.NET Core 文档中了解有关这些内容的更多信息。

关于c# - ASP.NET Core 中的内容类型 "415 Unsupported Media Type"为 "application/csp-report",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59811255/

相关文章:

blazor - HttpClient 出现问题 - blazor 中的 PostAsJsonAsync

javascript - 未捕获的类型错误 : Cannot read property 'locals' of undefined

c# - 使用 Application Insights 的 Azure Function 中出现内存不足异常

c# - 为什么 Enumerable.Count() 抛出 `InvalidOperationException` 以将 `null` 转换为 `bool` ?

c# - 使用反射获取类属性信息不返回任何内容

c# - Azure C# - 如何从不记名 token 获取用户详细信息

c# - WPF:在 XAML 中设置 ItemSsource 与代码隐藏

c# - 在同一主机和端口下运行多个应用程序

c# - 身份用户管理器 DeleteAsync DbUpdateConcurrencyException

asp.net-mvc - Asp.Net 3.1 使用 Windows 身份验证和角色授权