Pages

Friday, 5 August 2016

Google Recaptcha with server side validation in asp.net (C#)



For setting up google recaptcha and validate it on client side, you can read our previous article here
To validate your google recaptcha on server side in asp.net(C#), you can use following method which needs your google recaptcha secret key(you can generate your site key and secret key by using Generate Google recaptcha site key and secret key) in place of  "YourRecaptchaSecretkey" in the following code.



public bool IsValidCaptcha()
{
   string resp = Request["g-recaptcha-response"];
   var req = (HttpWebRequest)WebRequest.Create
("https://www.google.com/recaptcha/api/siteverify?secret="+ YourRecaptchaSecretkey + "&response=" + resp);
//Google recaptcha Response
    using (WebResponse wResponse = req.GetResponse())
          {
        using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
             {
              string jsonResponse = readStream.ReadToEnd();
              JavaScriptSerializer js = new JavaScriptSerializer();
              // Deserialize Json
              CaptchaResult data = js.Deserialize<CaptchaResult>(jsonResponse);
                if (Convert.ToBoolean(data.success))
                  {
                   return true;
                  }
             }
          }
   return false;

}


and also you need to create a class as shown below.


public class CaptchaResult
{
    public string success { get; set; }
}

Now you can validate your google recaptcha by calling "IsValidCaptcha()" method.

5 comments:

  1. Really found this helpful, thanks for sharing this

    ReplyDelete
  2. my production server don't have internet connection how can i call Google web service?

    ReplyDelete
  3. It 's an amazing article and useful for developers
    Dot Net Online Training

    ReplyDelete
  4. So, I seem to be missing the final step and its not working "Now you can validate your google recaptcha by calling "IsValidCaptcha()" method." How do you do this?

    ReplyDelete