asp.net core 中的 csp-report 端点

我正在尝试在 asp.net core web 应用程序中设置 CSP,并且 CSP 部分工作正常,我可以在浏览器控制台中看到违规行为,因为它们被发送到 report-uri 端点。


但是,我似乎无法在控制器中创建正确的方法来接收这些消息!


我在控制器中创建一个方法:


[HttpPost]

[AllowAnonymous]

public IActionResult UriReport(CspReportRequest request)

{

    _log.LogError("CSP violation: " + request);

    return Ok();

}

它会被调用,但“request”参数始终为空。一些搜索表明我需要使用 [FromBody] 属性从正文中读取数据,但是一旦我将其放入,它就不再被调用。 (CspReportRequest 是一个具有与 csp-report 有效负载匹配的属性的类,但它也不适用于字符串类型。)


因此,进一步阅读建议我为正文发送的“application/csp-report”内容类型添加一个处理程序:


services.Configure<MvcOptions>(options => {

    options.InputFormatters.OfType<JsonInputFormatter>().First().SupportedMediaTypes.Add(

        new MediaTypeHeaderValue("application/csp-report"));

});

但这似乎没有什么区别。


那么 - 我如何制作正确的控制器签名和/或正确的服务处理程序选项来接收数据。


梵蒂冈之花
浏览 208回答 3
3回答

摇曳的蔷薇

要使这项工作成功,需要做两件事。第一个是添加[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您感兴趣的具体信息。

侃侃尔雅

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

慕的地10843

&nbsp; &nbsp; &nbsp; &nbsp; .AddMvcOptions(options => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; options.InputFormatters.OfType<NewtonsoftJsonInputFormatter>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .First(f => f.SupportedMediaTypes.Contains("application/json"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .SupportedMediaTypes.Add("application/csp-report");&nbsp; &nbsp; &nbsp; &nbsp; });可能没有,JsonInputFormatter但NewtonsoftJsonInputFormatter如果你使用.AddNewtonsoftJson()另外,请注意第一个谓词。关键是有几个继承自JsonInputFormatter(一个用于补丁)的格式化程序,并且您对已经支持的那个格式化程序感兴趣application/json
打开App,查看更多内容
随时随地看视频慕课网APP