Introduction
In this tutorial, i will show you how to implement Google reCAPTCHA in ASP.NET MVC.
Implementation
First, go to Google reCAPTCHA and click the Get reCAPTCHA
button.
You will have to sign in with your Google account.
Choose the reCAPTCHA v2 option and add your domain in the list of domins (you can add more than one domain) or localhost if you
are working in a local environment. click the Register
button to register your site.
You will get two keys: a Site key and a Secret key.
To simplify the use of reCAPTCHA, download and install the ReCaptcha-Asp-Net package from GitHub or simply execute this command in NuGet package manager console.
Install-Package ReCaptcha-AspNet
Now, in the Web.config under the appSettings section add your secret and public keys
<add key="recaptcha-public-key" value="*** Your public key ***" />
<add key="recaptcha-secret-key" value="*** Your private key ***" />
In your HTML form add the GetCaptcha method to show the captcha.
[HttpPost]
public ActionResult Test() {
string captchaResponse = Request.Form["g-recaptcha-response"];
if (ReCaptcha.ValidateCaptcha(captchaResponse)) {
return View();
}
// A Bot
return RedirectToAction("Robot");
}
In preceding code, we get the captcha response from the user and we validate it by using the ValidateCaptcha method
of the ReCaptcha
class.
Namespace
to use the different methods of the ReCaptcha
class, you have to include the following namespace both in your view and controller.
using hbehr.recaptcha;