我的内容安全政策导致 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");
});
这是一个两步过程:
- 询问已配置的输入格式化程序列表以查找
SystemTextJsonInputFormatter
. - 添加
application/csp-report
添加到其现有的受支持媒体类型列表(application/json
、text/json
和application/*+json
)。
如果您使用 Json.NET 而不是 System.Text.Json
,方法类似:
services.AddControllers(options =>
{
var jsonInputFormatter = options.InputFormatters
.OfType<NewtonsoftJsonInputFormatter>()
.First();
jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report");
})
有两个小差异:
- 类型为
NewtonsoftJsonInputFormatter
而不是SystemTextJsonInputFormatter
. - 集合中有两个此类型的实例,因此我们定位第一个(有关具体信息,请参阅 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/