“415 不支持的媒体类型"对于内容类型“application/csp-report";在 ASP.NET Core 中 [英] "415 Unsupported Media Type" for Content-Type "application/csp-report" in ASP.NET Core
问题描述
我有一项内容安全政策,导致 Chrome 发布报告,但接收报告的操作返回415 不支持的媒体类型".我理解这是因为该帖子的 Content-Type 为application/csp-report".我如何将其添加为 Core 3.1 中允许的内容类型(它基本上只是 json).
I have a content security policy that causes Chrome to post a report, but the action that receives the report returns "415 Unsupported Media Type". I understand this is because the post has a Content-Type of "application/csp-report". How do I add this as a allowed content type in Core 3.1 (its basically just 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
的支持以处理其他媒体类型:
The following example shows how to add support to the SystemTextJsonInputFormatter
for handling additional media-types:
services.AddControllers(options =>
{
var jsonInputFormatter = options.InputFormatters
.OfType<SystemTextJsonInputFormatter>()
.Single();
jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report");
});
这是一个两步过程:
- 查询输入格式器的配置列表以找到
SystemTextJsonInputFormatter
. - 将
application/csp-report
添加到其现有支持的媒体类型列表(application/json
、text/json
和 <代码>应用程序/*+json).
- Interrogate the configured list of input-formatters to find the
SystemTextJsonInputFormatter
. - Add
application/csp-report
to its existing list of supported media-types (application/json
,text/json
, andapplication/*+json
).
<小时>
如果您使用的是 Json.NET 而不是 System.Text.Json
,方法是类似:
services.AddControllers(options =>
{
var jsonInputFormatter = options.InputFormatters
.OfType<NewtonsoftJsonInputFormatter>()
.First();
jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report");
})
有两个小的区别:
- 类型是
NewtonsoftJsonInputFormatter
而不是SystemTextJsonInputFormatter
. - 集合中有两个这种类型的实例,所以我们定位第一个(参见这个答案 的细节).
- The type is
NewtonsoftJsonInputFormatter
instead ofSystemTextJsonInputFormatter
. - There are two instances of this type in the collection, so we target the first (see this answer for the specifics).
<小时>
参见 Input Formatters 以了解有关这些内容的更多信息.
See Input Formatters in the ASP.NET Core docs to learn more about those.
这篇关于“415 不支持的媒体类型"对于内容类型“application/csp-report";在 ASP.NET Core 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!