3 回答

TA贡献1793条经验 获得超6个赞
要使这项工作成功,需要做两件事。第一个是添加[FromBody]
到您的CspReportRequest request
参数1:
public IActionResult UriReport([FromBody] CspReportRequest request)
如果没有[FromBody]
,JsonInputFormatter
将不会用于解析请求正文。但是,使用 后 [FromBody]
,您将开始看到415
响应。
第二件事是配置JsonInputFormatter
支持application/csp-report
媒体类型,您已经尝试过这样做。您的方法的问题在于,实际上有两个配置实例JsonInputFormatter
,而您影响了错误的实例。如果你只是从 2 更改First()
,Last()
它应该可以工作。
为什么?集合中的第一个JsonInputFormatter
实际上是 的实例JsonPatchInputFormatter
,它扩展了JsonInputFormatter
:
public class JsonPatchInputFormatter : JsonInputFormatter
这是第一个添加的,因此它是您正在配置的。它无法处理 的实例,CspReportRequest
因为它有关于处理JsonPatchDocument<T>
等的特定规则,因此它会传递到第二个JsonInputFormatter
。正如我所提到的,第二个实例未配置为支持application/csp-report
,因此它也无法处理该请求。
1如果您正在使用[ApiController]
,则不需要使用[FromBody]
,但您问题中的所有内容都表明您没有使用[ApiController]
。
2使用Last()
notFirst()
不一定是最好的方法,但它应该表明问题出在哪里。有很多方法可以获取JsonInputFormatter
您感兴趣的具体信息。

TA贡献1801条经验 获得超16个赞
另一种选择是读取 Request.Body 来获取报告。
不要忘记包含 Microsoft.AspNetCore.Mvc 命名空间。
[HttpPost]
public IActionResult Report()
{
var report = "";
using (var reader = new StreamReader(Request.Body))
{
report = reader.ReadToEnd();
}
_log.LogError("CSP violation: " + report);
return Ok();
}
报告变量将包含 json 报告数据。

TA贡献1785条经验 获得超8个赞
.AddMvcOptions(options => {
options.InputFormatters.OfType<NewtonsoftJsonInputFormatter>()
.First(f => f.SupportedMediaTypes.Contains("application/json"))
.SupportedMediaTypes.Add("application/csp-report");
});
可能没有,JsonInputFormatter但NewtonsoftJsonInputFormatter如果你使用.AddNewtonsoftJson()
另外,请注意第一个谓词。关键是有几个继承自JsonInputFormatter(一个用于补丁)的格式化程序,并且您对已经支持的那个格式化程序感兴趣application/json
- 3 回答
- 0 关注
- 144 浏览
添加回答
举报