This project is read-only.

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

Pre-requisites

Please ensure that you have completed the following steps:

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:"6LdkfdwSAAAAABL1099CPTr6473FQFXNLR_04Bb5", privateKey:"6LdkfdwSAAAAAFC8jtUY44wuhC9lmDlFrL6qMAAh")

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: 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 = await 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.

See Also

Last edited Feb 27, 2013 at 7:21 AM by tanveery, version 18

Comments

Joschka Jul 2, 2016 at 10:52 AM 
Well, I've resolved my own problem with "await" while recreating the entire project a few times; eventually, I noticed a checkbox for 'async methods' and I checked that.

Now the supplied code compiles without errors or warnings.

Joschka Jul 1, 2016 at 3:08 PM 
Neither of these versions compile:
RecaptchaVerificationResult recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponse();
RecaptchaVerificationResult recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponseTaskAsync();

Because "async" is invalid. I could not find a way around this. Can anyone help? I'm so close to making this work!

Famcosoft May 27, 2016 at 5:42 AM 
"INVALID PRIVATE KEY" = Dumb mistake on my behalf but when i copied it from the first page it did not copy the whole number. I had a "-abc" and had to add this. Silly but it took me a few minutes. hope this helps someone.

jmichas Apr 13, 2015 at 4:52 PM 
Oops! Sorry, the method should have been
public override void OnActionExecuting(ActionExecutingContext filterContext)
otherwise it doesnt get validated before the action code runs and ModelState would be valid regardless of whether the captcha was filled in or correct.

jmichas Apr 13, 2015 at 3:59 PM 
I like the whole idea but I dont want to have to write the controller code all the time. So, I wrote an ActionFilter instead. Add this class to your project and then you can just decorate your controller action with [ValidateRecaptchaResponse].

public class ValidateRecaptchaResponseAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var controller = filterContext.Controller as Controller;
if(controller == null) throw new NullReferenceException("filterContext.Controller cannot be null");

var recaptchaHelper = controller.GetRecaptchaVerificationHelper();

if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
controller.ModelState.AddModelError("", "Captcha answer cannot be empty.");
}
else
{

var recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

if (recaptchaResult != RecaptchaVerificationResult.Success)
{
controller.ModelState.AddModelError("", "Incorrect captcha answer.");
}
}
}
}

Pholux Dec 2, 2014 at 6:42 PM 
I was having the same problem, getting "Invalid Private key" error message... the problem was that I put the private key and public key in the VIEWS web.config file and not in the global web.config file.... now is working flawlessly

sujoya Nov 11, 2014 at 3:06 AM 
Can someone help me. I am facing a problem, the recaptcha is not able to validate properly because it is somehow not taking the private key provided by me in the web.config file. I have written the following code in the controller action method:
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("Captcha", "Incorrect captcha answer.");
return View(model);
}

When I check the value of recaptchaResult.ToString() , it is always returning "InvalidPrivateKey"

I have created entries for the private and public keys in web.config as follows:

<add key="recaptchaPublicKey" value="6Lf9av0S------4r" />
<add key="recaptchaPrivateKey" value="6Lf9av0SA ------Ai" />

In the view file (.cshtml) I have placed the captcha in the following way:
@Html.Recaptcha(publicKey:"6Lf9av0SAAAAAPC0DXH3niU7BKG0Kuu7ajbNd_4r")

I am not able to specify the private key in the above extension method (as mentioned in this documentation) because I get the compile error "The best overload for 'Recaptcha' does not have a parameter named 'privateKey' "

I am using MVC 4 in Visual Studio 2012 environment and ASP.NET framework 4.0 and Recaptcha.Web.dll, v1.6.0.0

Regards,

kyle_peters Aug 29, 2014 at 3:59 AM 
I got this working wonderfully in a View, but the reCatcha doesn't display in a PartialView called via ajax. Can anyone assist me, or does this simply not work in a PartialView called via ajax?

smokenmirraz May 22, 2014 at 1:04 AM 
Installation, setup, and usage were very easy thanks to the excellent documentation provided. Thanks.

Acky Jun 13, 2013 at 8:47 PM 
SOLVED:
For anyone else having trouble with this, the answer is in the compiler error.

Originally the Register method definition was:
public ActionResult Register(RegisterModel model)

To use the asynchronous version in the 2nd example, change the method definition to:
public async Task<ActionResult> Register(RegisterModel model)

Which will also require you to add another using statement if you don't already have it
using System.Threading.Tasks;

Acky Jun 11, 2013 at 11:51 PM 
I'm creating an MVC 4 asp.net application in VS 2012 using your recaptcha pacakge.

When trying to use the asynchronous result from the 2nd example:
RecaptchaVerificationResult recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponseTaskAsync();

I'm getting the following error in the compiler:
Error 2 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<System.Web.Mvc.ActionResult>'.


This is after installing the nu-get package by using right click on the project's References section and using "Manage NuGet packages" to install the package. According to the NuGet package manager, I'm using Version 1.2.

For now, I'm having to use a slightly modified version of the 1st example:
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

Which I'm assuming is a bad idea on a site with a lot of traffic?