Use reCAPTCHA in ASP.NET

In this post we are going to explain how to use reCAPTCHA in an ASP.NET. application.

It is easy and intuitive to integrate Google’s reCAPTCHA  but you have to pay attention to some “validation” details that we are going to see in the course of the post.

First of all, you need to sign up to get 2 registration keys, a public one and a private one that will have to be used during the integration of this component within the APSX page.

You can download the DLL to be integrated within the site from here.

It is easy to Integrate the library and it can be done by following these steps:

1) Add the library Reference downloaded in VS.

2) Register the dll in the web.config file if you need to reuse the library in several pages

<pages>
   <controls>
      <add tagPrefix="recaptcha" assembly="Recaptcha" namespace="Recaptcha" />
   </controls>
</pages>

Or in the page in which you want to integrate the reCAPTCHA

<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

3) Put the reCAPTCHA control in a tag <form runat=”server”>

<recaptcha:RecaptchaControl
    ID="recaptcha"
    runat="server"
    PublicKey="your_public_key"
    PrivateKey="your_private_key"
    />

This is what you need to integrate the control within the web application

Everything is fine up to now!

Now let’s see how to solve some problems like the validation of the page and of the reCAPTCHA and especially the hosting security problems.

First, let’s see how to solve the problems related to the hosting servers rights.

As you don’t have the rights in full trust, you can’t invoke the assembly.

The solution to the security problem

You can solve this problem by doing the following things:

  • Download the reCAPTCHA library sources for ASP.NET by checking out from here
  • Open the solution and change the rights in the AssemblyInfo.cs file, like this:
[assembly: AllowPartiallyTrustedCallers()]
  • Fill in and copy the new assembly in your solution ASP.NET.

The validation

To validate the reCAPTCHA control is very easy. Add this code to the button click event that submits the form.

protected void ButtonSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
< processate il form >
}
else
{
< visualizzate un errore >
}
}

This code works perfectly if you don’t have validations on other controls.

To overcome the following problem, you have to validate the control Recaptcha in a different way.

Within the same method as above, you have to include this type of validation in order to have the coexistence of the traditional validation on asp.net controls and the recapcha control.

recaptcha.Validate();
if (recaptcha.IsValid)
{
< processate il form >
}
else
{
< visualizzate un errore >
}

And this is it!