"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
和application/*+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
,则方法与相似:
If you're using Json.NET instead of System.Text.Json
, the approach is similar:
services.AddControllers(options =>
{
var jsonInputFormatter = options.InputFormatters
.OfType<NewtonsoftJsonInputFormatter>()
.First();
jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report");
})
有两个小区别:
- 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).
See Input Formatters in the ASP.NET Core docs to learn more about those.
这篇关于"415不支持的媒体类型";用于内容类型"application/csp-report".在ASP.NET Core中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!