Search code examples
c#asp.net-web-apiasp.net-web-api2recaptcha

Google reCaptcha in Web API 2 c#


I have an ASP.NET Web API 2 Project. I am trying to read Google Captcha from the form. I tried this Code:

    public string Post(FoundingRequest model)
    {
        var response = Request["g-recaptcha-response"];
        string secretKey = "my key";
        var client = new WebClient();
        var result = client.DownloadString(
        $"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={response}");
        var obj = JObject.Parse(result);
        model.Captcha = (bool)obj.SelectToken("success");
        ....
    }

but I am receiving an Error on the first line:

Cannot apply indexing with [] to an expression of type 'HttpRequestMessage'

why? and how to solve it? thank you


Solution

  • I found the answer, I created a hidden input with a certain name and updated its value on Captcha call back. Code:

       <input type="hidden" value="" id="recaptcha" name="recaptcha" />
       <div class="g-recaptcha" data-callback="imNotARobot" data-sitekey="key"></div>
    

    and the Javascript is:

    <script type="text/javascript">
        var imNotARobot = function () {
           $("#recaptcha").val(grecaptcha.getResponse());
        };
    </script>
    

    server side:

    public string Recaptcha { get; set; }
    

    and the model binder does all the work.