Recaptcha.MVC

Description:

Recaptcha.MVC is a nuget package that provides ASP.NET MVC applications with helper methods for including and verifying Google reCAPTCHA codes.

Available at: nuget.org

Installation:

PM> Install-Package RecaptchaMVC

How to use:

Recaptcha.MVC has been built to work with Google reCAPTCHA.

1. Sign up for Google reCAPTCHA

Go to https://www.google.com/recaptcha/admin to register your site for reCAPTCHA (requires a Google account).

2. Add entries to your web.config file

Once you have registered for Google reCAPTCHA, you should have been given two keys:

  • Site key
  • Secret key

Add these keys into the AppSettings section of your web.config file, like this:

<add key="Captcha:SharedKey" value="{your site key}" />
<add key="Captcha:SecretKey" value="{your secret key}" />

Also add an entry for the Google reCAPTCHA verification url, like this:

<add key="Captcha:VerifyUrl" value="https://www.google.com/recaptcha/api/siteverify" />

3. Add the reCAPTCHA components to your HTML form

The Recaptcha.MVC component contains HtmlHelper extension methods for adding the required reCAPTCHA components to your HTML form.

To add a reference to the reCAPTCHA javascript file:

@Html.IncludeRecaptchaScriptReference()

To add the reCAPTCHA component to your form:

@Html.Recaptcha()

4. Validate the reCAPTCHA code on the server side

In your MVC controller class, include the following using statement:

using Recaptcha.MVC.Validation;

Then call the IsValidCaptcha() extension method to validate the CAPTCHA response. The extension method is available for both the HttpRequest or HttpRequestBase classes.

var captchaResponse = this.Request.IsValidCaptcha();

if (captchaResponse.Success != true)
{
...
}

Calling the IsValidCaptcha() method will return an instance of CaptchaResponse class.

public class CaptchaResponse
{
public bool Success { get; set; }

[JsonProperty("error-codes")]
public IList<string> ErrorCodes { get; set; }
}

Checking the Success boolean property will determine if the verification was successful.

If the verification was not successful then a list of error codes are included in the ErrorCodes property.