模型绑定CSP报告json

时间:2016-05-03 10:29:34

标签: c# asp.net json model model-binding

我正在尝试创建一个网址,我的网站可以发布CSP违规行为但是我发现在没有我自己的自定义模型绑定器的情况下模拟绑定非常困难。

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; }
}

如何访问包含" - "的参数?炭。

以下仅绑定"引用者"属性:

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; }
}

1 个答案:

答案 0 :(得分:1)

就个人而言,我只是跳过了整个绑定机制,直接进入了内容体:

    [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;
        }
    }