我正在尝试创建一个我的网站可以发布 CSP 违规的 URL,但我发现如果没有我自己的自定义模型绑定程序,模型绑定非常困难。
CSP json 是什么样的:
{
"csp-report": {
"document-uri": "https://example.com/foo/bar",
"referrer": "https://www.google.com/",
"violated-directive": "default-src self",
"original-policy": "default-src self; report-uri /csp-hotline.php",
"blocked-uri": "http://evilhackerscripts.com"
}
}
这里有两个主要问题。访问嵌套属性,那么如何访问 csp-report 对象内部的属性。
此模型仅返回 null:
public class CspReportRequest
{
[JsonProperty(PropertyName = "csp-report")]
public CspReport CspReport { get; set; }
}
public class CspReport
{
[JsonProperty(PropertyName = "document-uri")]
public string DocumentUri { get; set; }
[JsonProperty(PropertyName = "referrer")]
public string Referrer { get; set; }
[JsonProperty(PropertyName = "violated-directive")]
public string ViolatedDirective { get; set; }
[JsonProperty(PropertyName = "original-policy")]
public string OriginalPolicy { get; set; }
[JsonProperty(PropertyName = "blocked-uri")]
public string BlockedUri { get; set; }
}
如何访问包含“-”字符的参数。
以下仅绑定“referrer”属性:
json:
{
"document-uri": "https://example.com/foo/bar",
"referrer": "https://www.google.com/",
"violated-directive": "default-src self",
"original-policy": "default-src self; report-uri /csp-hotline.php",
"blocked-uri": "http://evilhackerscripts.com"
}
型号:
public class CspReport
{
[JsonProperty(PropertyName = "document-uri")]
public string DocumentUri { get; set; }
[JsonProperty(PropertyName = "referrer")]
public string Referrer { get; set; }
[JsonProperty(PropertyName = "violated-directive")]
public string ViolatedDirective { get; set; }
[JsonProperty(PropertyName = "original-policy")]
public string OriginalPolicy { get; set; }
[JsonProperty(PropertyName = "blocked-uri")]
public string BlockedUri { get; set; }
}
就我个人而言,我只是跳过了整个绑定机制,直接进入内容主体:
[HttpPost]
public async Task<bool> Post()
{
try
{
string content = await Request.Content.ReadAsStringAsync().ConfigureAwait(false);
CspReportRequest cspReport = JsonConvert.DeserializeObject<CspReportRequest>(content);
//Do Stuff Here!!
return true;
}
catch(Exception ex)
{
return false;
}
}