ASP.NET Core 3.1处理application/csp-report类型415错误方案
解决ASP.NET Core 3.1中CSP报告的415 Unsupported Media Type错误
问题原因
Chrome发送的CSP报告请求Content-Type是application/csp-report,虽然它本质是JSON格式,但ASP.NET Core默认的JSON输入格式化器只支持application/json、text/json等标准JSON媒体类型,不会自动识别application/csp-report,因此会返回415错误。
解决方案
我们需要将application/csp-report添加到JSON输入格式化器的支持媒体类型列表中,有两种配置方式:
1. 全局配置(推荐)
在Startup.cs的ConfigureServices方法中,修改AddControllers的配置,给JSON格式化器添加目标媒体类型:
使用System.Text.Json(ASP.NET Core 3.1默认)
using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Net.Http.Headers; public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddJsonOptions(options => { // 可选:设置属性名不区分大小写,适配CSP报告的下划线命名 options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; // 找到SystemTextJsonInputFormatter并添加application/csp-report支持 var jsonInputFormatter = options.InputFormatters.OfType<SystemTextJsonInputFormatter>().FirstOrDefault(); if (jsonInputFormatter != null) { jsonInputFormatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/csp-report")); } }); }
使用Newtonsoft.Json(如果你替换了默认序列化器)
如果项目中使用的是Newtonsoft.Json(Json.NET),配置方式如下:
using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Net.Http.Headers; using Newtonsoft.Json.Serialization; public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(options => { // 可选:配置驼峰命名解析,适配CSP报告格式 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 找到NewtonsoftJsonInputFormatter并添加支持类型 var jsonInputFormatter = options.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().FirstOrDefault(); if (jsonInputFormatter != null) { jsonInputFormatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/csp-report")); } }); }
2. 局部配置(仅针对单个Action)
如果你只想让特定的Action支持application/csp-report,除了保留你现有的[Consumes("application/csp-report")]属性外,仍需要完成上面的全局格式化器配置(因为核心是让JSON解析器识别该媒体类型)。你的Action和模型代码可以保持不变:
// Action代码 [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; } // 可以根据需要添加其他CSP报告字段,比如violated-directive、original-policy等 }
测试验证
你可以用Postman或curl发送测试请求:
- 请求方法:POST
- 请求地址:你的报告接口地址(比如
/csp-report) - Content-Type:
application/csp-report - 请求Body示例:
{ "csp-report": { "document-uri": "https://yourdomain.com/page", "violated-directive": "script-src 'self'", "original-policy": "script-src 'self'; report-uri /csp-report" } }
发送请求后应该能收到200 OK的响应,说明接口已经可以正确解析CSP报告了。
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

