Introduction
In this article, we will learn how to integrate Google reCHAPTCHA using JavaScript code in a web application, in my case, I am implementing functionality in the .NET MVC application. In order to integrate Google reCAPTCHA we require SiteKey and SecretKey for a web application which we can get from Google's Developer account. Please refer to my earlier article to get Google reCAPTCHA's keys.
Why Google reCAPTCHA is required?
it's a free service provided by Google with just a few configurations and setups. It helps our website from spam and attacks. As humans can easily solve the "CAPTCHA" test bots and malicious software can not help us to prevent those attacks.
Let's start the integration of Google reCAPTCHA step by step.
Step 1. Import system.net library or namespace from references.
using System.Net;
Step 2. In order to use Google reCAPTCHA, we require key, secret, and response fields as a Model class. Please create the below modal class with exactly the same properties.
public class reCaptcha
{
public string Response { get; set; }
public string Secret = "<reCAPTCHA Secret Key>";
public string Key = "<reCAPTCHA Site Key>";
}
Step 3. To handle the actions of Google reCAPTCHA, we need to declare a two-action method. These action methods are used to initialize CAPTCHA to our page and handle captcha responses from Google.
From below AjaxMethod - this action method will help us to handle calls from JavaScript AJAX calls. Basically, it will call the Google reCAPTCHA API and verify the user, in return, the response will be saved into the response property of the model class as a JSON value.
public class LoginController : Controller
{
public ActionResult Login()
{
return View(new reCaptcha());
}
[HttpPost]
public JsonResult AjaxMethod(string response)
{
reCaptcha recaptcha = new reCaptcha();
string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + recaptcha.Secret + "&response=" + response;
recaptcha.Response = (new WebClient()).DownloadString(url);
return Json(recaptcha);
}
}
Step 4. Now we need to configure the AJAX call for verification and handle captcha verification on our VIEW(.cshtml) page.

Join the conversation! Your thoughts help the community grow.