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

本文关键字:g-repatcha-response ApiController NET ASP | 更新日期: 2023-09-27 18:21:33

我正在尝试将带有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-repatcha-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; }
}

但显然CCD_ 2和CCD_。有效的属性名称不应包含短划线-

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

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

以下是我的发现:

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