Resources /
ASP NET / Add ReCaptcha to MVC Razor 3 Application
Add ReCaptcha to a MVC Razor 3 Application
I read a lot of tutorials on how to do this but none of them really covered EVERY step. This one does.
1. Create a new project in Visual Studio.
Visual Studio File > New Project > ASP.NET MVC 3 Web Application > TestReCaptcha > Internet Application with the view engine set to Razor.
2. Run it and go to /Account/Register. This is where we will add the CAPTCHA.
3. Sign up at reCaptcha, http://recaptcha.net/whyrecaptcha.html and get a private and public key.
4. Download the zip file below http://www.yart.com.au/admin/file/content2/c7/captcha.zip. Add the dll to your bin folder. Add a reference in Visual Studio to it. Copy captcha.cs into your Models directory.
Note that cpatcha.cs is a slight modification of the ideas here http://devlicio.us/blogs/derik_whittaker/archive/2008/12/02/using-recaptcha-with-asp-net-mvc.aspx
Note also that we are assuming your project is named TestReCaptcha as this is used as the namespace throughout.
5. Change the private and public key at the top of captcha.cs
6. Go to /Views/Account/Register.cshtml and add this at the top of the file:
@using TestReCaptcha.Models
7. Add this code to the same file after the Remember Me html.
<div class="editor-label">Type in the characters below</div>
<div class="captcha">
@Html.Generate()
</div>
<span class="field-validation-error">@ViewBag.CaptchaError</span>
8. When you run the project and go to Account/Register you should see the Captcha.
9. Modify the Account/LogOn Post Controller
[CaptchaValidator]
[HttpPost]
public ActionResult Register(RegisterModel model, bool captchaValid)
{
if (ModelState.IsValid && captchaValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
if (createStatus == MembershipCreateStatus.Success)
{
FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
if (!captchaValid)
ViewBag.CaptchaError = "The characters do not match the image above";
ViewBag.PasswordLength = MembershipService.MinPasswordLength;
return View(model);
}
10.Test the code by running /Account/Register and completing all information correctly except for the Captcha. You should see an error message. Note that if you do enter all information correctly including the Captcha you will need to create a SQL database as this has not been set up.
11. That's it! If you have any divine insights/improvements with Captcha please email us via the Contact link.