/recaptcha-net

reCAPTCHA for .NET library lets you easily use Google's reCAPTCHA in an ASP.NET Web Forms / MVC application.

Primary LanguageC#Apache License 2.0Apache-2.0

reCAPTCHA library for .NET

reCAPTCHA for .NET is one of the most popular and well-documented reCAPTCHA libraries used by thousands of .NET developers in their ASP.NET web forms and MVC applications. The library is created and maintained by @tanveery.

Features

The primary features of the library are:

  • Render recaptcha control (HTML) with appropriate options for pre-defined themes and culture (language).
  • Verify user's answer to recaptcha's challenge.
  • Supports ASP.NET Web Forms and ASP.NET MVC.
  • Supprts reCAPTCHA version 1 and version 2 in a seamless fashion.
  • One of the most well-documented reCAPTCHA libraries in the open source community.

API Support

The library supports Google's reCATPCAH API version 1 and version 2 in a seamless fashion. To switch between the two APIs, all you need is to set 1 or 2 as a value to the recaptchaApiVersion app settings key.

Creating a reCAPTCHA API Key

Before you can use reCAPTCHA in your web application, you must first create a reCAPTCHA API key (a pair of public and private keys). Creating reCAPTCHA API key is very straight-forward. The following are the steps:

  1. Go to the Google's reCAPTCHA site.
  2. Click on the Get reCAPTCHA button. You will be required to login with your Google account.
  3. Under the Register a new site section, enter a label and the domain of your web application. You can enter more than one domain if you want to. Optionally, you can add one more owners of this new reCAPTCHA API key.
  4. Click on the Register button.
  5. Under the Adding reCAPTCHA to your site section, take note of your Site Key and Secret Key which you would need to specify in your application's web.config file.

Installation

reCAPTCHA Nuget Package

The best and the recommended way to install the latest version of reCAPTCHA for .NET is through Nuget. From the Nuget's Package Manager Console in your Visual Studio .NET IDE, simply execute the following command:

PM> Install-Package RecaptchaNet

Latest Release

You can also download a released build of reCAPTCHA for .NET by going to the Releases section of this project. The latest release is reCAPTCHA for .NET v2.0.

Issues

If you find a bug in the library or you have an idea about a new feature, please try to search in the existing list of issues. If the bug or idea is not listed and addressed there, please open a new issue.

Quick Starter

How to Use reCAPTCHA in an ASP.NET Web Forms Application

Add the following line just under the Page directive in your .aspx or .ascx file:

<%@ Register Assembly="Recaptcha.Web" Namespace="Recaptcha.Web.UI.Controls"
TagPrefix="cc1" %>

Then at the desired line in the same file add the reCAPTCHA control as follows:

<cc1:Recaptcha ID="Recaptcha1" PublicKey="Your site key"
PrivateKey="Your secret key" runat="server" />

Rather than setting the recaptcha key of the control through its PublicKey and PrivateKey properties, you can set them in your web.config file instead:

How to Set Recaptcha Key in Web.config File

How to Set Recaptcha Key in Web.config File

After you set the private and public keys in your web.config file, all you need in your web form is this following piece of code:

<cc1:Recaptcha ID="Recaptcha1" runat="server" />

By default, the theme of the reCAPTCHA control is Red. However, you can change this default theme to one of the other three themes if you like. Those themes are: Blackglass, White, and Clean. Theme can be set by using the RecaptchaTheme enum. The following is an example:

<cc1:Recaptcha ID="Recaptcha1" Theme="RecaptchaTheme.Clean" runat="server" />

Add the reCAPTCHA Control to the Visual Studio Toolbox

Instead of writing the above code manually, you can easily drag and drop the same reCAPTCHA control from the Visual Studio Toolbox onto your page designer just like the way you would do for other standard ASP.NET controls. However, you would need to add the reCAPTCHA control to the Toolbox first. Simply, right click on the Toolbox and select Choose Items... from the context menu and then under the .NET Framework Components tab click on the Browse button and locate the Recaptcha.Web.dll assembly.

Verify User's Response to reCAPTCHA Challenge

When your end-user submits the form that contains the reCAPTCHA control, you obviously would want to verify whether the user's answer was valid based on what was displayed in the recaptcha image. It is very easy to do with one or two lines.

First of all as expected, import the namespace Recaptcha.Web in your code-behind file:

using Recaptcha.Web;

To verify whether the user's answer is correct, call the control's Verify() method which returns RecaptchaVerificationResult. You can also use the control's Response property to check what the actual answer is. Generally, you would want to use the Response property to check if the user provided a blank response which of course is always wrong:

if (String.IsNullOrEmpty(Recaptcha1.Response))
{
    lblMessage.Text = "Captcha cannot be empty.";
}
else
{
    RecaptchaVerificationResult result = Recaptcha1.Verify();
    if (result == RecaptchaVerificationResult.Success)
    {
        Response.Redirect("Welcome.aspx");
    }
    if (result == RecaptchaVerificationResult.IncorrectCaptchaSolution)
    {
        lblMessage.Text = "Incorrect captcha response.";
    }
    else
    {
        lblMessage.Text = "Some other problem with captcha.";
    }
}

Instead of calling the Verify() method, you can call the VerifyTaskAsync() method to verify the user's response asynchronously which at the same time can be used along with the new await keyword:

if (String.IsNullOrEmpty(Recaptcha1.Response))
{
    lblMessage.Text = "Captcha cannot be empty.";
}
else
{
    RecaptchaVerificationResult result = await Recaptcha1.VerifyTaskAsync();
    if (result == RecaptchaVerificationResult.Success)
    {
        Response.Redirect("Welcome.aspx");
    }
    if (result == RecaptchaVerificationResult.IncorrectCaptchaSolution)
    {
        lblMessage.Text = "Incorrect captcha response.";
    }
    else
    {
        lblMessage.Text = "Some other problem with captcha.";
    }
}

How to Use reCAPTCHA in an ASP.NET MVC Web Application

Add the reCAPTCHA Control to Your MVC View

Add the following line at the top of your view (a .cshtml file):

@using Recaptcha.Web.Mvc;

Then at the desired line in the same file call the reCAPTCHA extension method of the HtmlHelper class as follows:

@Html.Recaptcha(publicKey:"Your site key", privateKey:"Your secret key")

Rather than setting the recaptcha key through the PublicKey and PrivateKey properties of the HtmlHelper's recaptcha extension, you can set them in your web.config file instead:

How to Set Recaptcha Key in Web.config File

After you set the private and public keys in your web.config file, all you need in your view is this following piece of code:

@Html.Recaptcha()

By default, the theme of recaptcha is Red. However, you can change this default theme to one of the other three themes if you like. Those themes are: Blackglass, White, and Clean. Theme can be set by using the RecaptchaTheme enum. The following is an example:

@Html.Recaptcha(theme:Recaptcha.Web.RecaptchaTheme.Clean);

Verify User's Response to reCAPTCHA Challenge

When your end-user submits the form that contains the reCAPTCHA control, you obviously would want to verify whether the user's answer was valid based on what was displayed in the recaptcha image. It is very easy to do with few lines.

First of all as expected, import the namespaces Recaptcha.Web and Recaptcha.Web.Mvc in your controller file:

using Recaptcha.Web;
using Recaptcha.Web.Mvc;

To verify whether the user's answer is correct, you need to create an instance of the RecaptchaVerificationHelper class by calling the extension method GetRecaptchaVerificationHelper() of the controller. You can then call the RecaptchaVerificationHelper object's VerifyRecaptchaResponse() method which returns a RecaptchaVerificationResult enum. You can also use the helper object's Response property to check what the actual answer of the user is. Generally, you would want to use the Response property to check if the user provided a blank response which of course is always wrong:

RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
    ModelState.AddModelError("", "Captcha answer cannot be empty.");
    return View(model);
}
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
    ModelState.AddModelError("", "Incorrect captcha answer.");
}

Instead of calling the VerifyRecaptchaResponse() method, you can call the VerifyRecaptchaResponseTaskAsync() method to verify the user's response asynchronously which at the same time can be used along with the new await keyword:

RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
    ModelState.AddModelError("", "Captcha answer cannot be empty.");
    return View(model);
}
RecaptchaVerificationResult recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponseTaskAsync();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
    ModelState.AddModelError("", "Incorrect captcha answer.");
}

Note: The GetRecaptchaVerificationHelper() is an extension method to the MVC's built-in Controller class. This means you must import the Recaptcha.Web.Mvc namespace explicitly at the top of the controller file otherwise the code will not compile.

How to Set reCAPTCHA Key in Web.config File

As you may have already seen, you can directly assign public and private keys to the respective properties of Recaptcha ASP.NET control or reCAPTCHA MVC HTML extension. However, a better way is to store these keys in your web.config file. The obvious benefit is that you can change these keys anytime you want without requiring you to modify your code and perhaps most important benefit is that you the keys you define in your web.config are global in your web project.

In the appSettings section of your web.config file, add the keys as follows:

<appSettings>
<add key="recaptchaPublicKey" value="Your site key" />
<add key="recaptchaPrivateKey" value="Your secret key" />
<add key="recaptchaApiVersion" value="2" />
</appSettings>

Note: The appSettings keys are automatically added to your web.config file if you install reCAPTCHA for .NET through Nuget. However, you would still need to provide your own public and private keys in the web.config file of your project.