"415不支持的媒体类型";用于内容类型"application/csp-report".在ASP.NET Core中 [英] "415 Unsupported Media Type" for Content-Type "application/csp-report" in ASP.NET Core

查看:165
本文介绍了"415不支持的媒体类型";用于内容类型"application/csp-report".在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");
});

这是一个两步过程:

  1. 询问已配置的输入格式器列表以找到SystemTextJsonInputFormatter.
  2. application/csp-report添加到其现有的受支持媒体类型(application/jsontext/jsonapplication/*+json)列表中.
  1. Interrogate the configured list of input-formatters to find the SystemTextJsonInputFormatter.
  2. Add application/csp-report to its existing list of supported media-types (application/json, text/json, and application/*+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");
})

有两个小区别:

  1. 类型是NewtonsoftJsonInputFormatter而不是SystemTextJsonInputFormatter.
  2. 集合中有两个此类实例,因此我们将第一个定位为目标(请参见
  1. The type is NewtonsoftJsonInputFormatter instead of SystemTextJsonInputFormatter.
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆