如何在ASP.NET ApiController中捕获g-recaptcha-response?

时间:2015-11-10 16:56:37

标签: c# asp.net-web-api2 recaptcha

我正在尝试将带有ReCaptcha的表单发布到ApiController。

<form>
    <label for="name">Name:</label>
    <input id="name" name="name" ><br/>    
    <label for="email">Email:</label>
    <input id="email" name="email" type="email" ><br/>
    <div class="g-recaptcha" data-sitekey="some_site_key"></div>
    <input type="submit" value="Submit"/>
</form>

<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
    $(function () {
        $('form').submit(function (event) {
            var data = $('form').serialize();
            console.log('form data: ', data);
            $.post("api/test", data,
                function (data) {
                alert('success');
            });
            event.preventDefault();
        });
    });
</script>

console.log()语句中,我可以看到发布的值在名称电子邮件 g-recaptcha-response

我以为我可以在ApiController上有一个视图模型,如下所示:

public IHttpActionResult Post(FormModel model)
{
   // automatic model binding to get the posted data.
}

public class FormModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string GRecaptchaResponse { get; set; }
}

但显然没有规则将g-recaptcha-response绑定到GRecaptchaResponse。有效的属性名称不应包含短划线-

所以问题是,我们如何才能在服务器(ApiController)端收到g-recaptcha-response值?

1 个答案:

答案 0 :(得分:0)

以下是我发现的内容:

在ApiController中:

public async Task Post()
{
    var obj = await Request.Content.ReadAsAsync<JObject>();
    var model = obj.ToObject<FormModel>();        
    //...
}

对于FormModel,请使用[JsonProperty]

public class FormModel
{
    public string Name { get; set; }
    public string Email { get; set; }

    [JsonProperty("g-recaptcha-response")]
    public string GRecaptchaResponse { get; set; }
}