Google reCaptcha in Web API 2 c#

混江龙づ霸主 提交于 2021-02-07 20:22:12

问题


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


回答1:


That method's body for me works fine:

 const string secretKey = "YOUR KEY";
            string responseFromServer = "";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + response);

            using (WebResponse resp = req.GetResponse())
            using (Stream dataStream = resp.GetResponseStream())
            {
                if (dataStream != null)
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        // Read the content.
                        responseFromServer = reader.ReadToEnd();
                    }
                }
            }

            dynamic jsonResponse = new JavaScriptSerializer().DeserializeObject(responseFromServer);

            return jsonResponse == null || bool.Parse(jsonResponse["success"].ToString());

Update

Regarding the comment, it can be checked on the client side

var response = window.grecaptcha.getResponse()

And then pass this variable to Web API

This is part of my client script:

      if (typeof window.grecaptcha != 'undefined') {
        var capResponse = window.grecaptcha.getResponse();

        if (!capResponse || capResponse.length === 0) {
            user.isCaptchaPassed = false;
            //alert("Captcha not Passed");
            return false;
        }

        user.gReCaptcha = capResponse;
    }

"user" is JS object created before, which passed through JS to server. (AJAX call)




回答2:


I found the answer, I created a hidden file with a certain name and update 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 binder does all the work.




回答3:


Here's how I did it. I don't use the ChallangeTs so I didn't bother trying to figure out why it wasn't converting to DateTime properly. Maybe someone else has that solved.

   public class ReCaptchaResponse
        {
            public bool Success;
            public string ChallengeTs;
            public string Hostname;
            public object[] ErrorCodes;
        }

        [HttpPost]
        [Route("captcha")]
        public bool Captcha([FromBody] string token)
        {
            bool isHuman = true;

            try
            {
                string secretKey = ConfigurationManager.AppSettings["reCaptchaPrivateKey"];
                Uri uri = new Uri("https://www.google.com/recaptcha/api/siteverify" +
                                  $"?secret={secretKey}&response={token}");
                HttpWebRequest request = WebRequest.CreateHttp(uri);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = 0;
                HttpWebResponse response = (HttpWebResponse) request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream);
                string result = streamReader.ReadToEnd();
                ReCaptchaResponse reCaptchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(result);
                isHuman = reCaptchaResponse.Success;
            }
            catch (Exception ex)
            {
                Trace.WriteLine("reCaptcha error: " + ex);
            }

            return isHuman;
        }



回答4:


I assume this request is coming from a form, change this:

var response = Request["g-recaptcha-response"];

To this:

var response = Request.Form["g-Recaptcha-Response"];

Also Change this:

var result = client.DownloadString($"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={response}");

To this:

var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));


来源:https://stackoverflow.com/questions/43327257/google-recaptcha-in-web-api-2-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!