Recaptcha In MVC

by Matt 21. August 2009 19:17

So you want to add a recaptcha to your MVC project, and don't know where to start.  Don't worry, I was there a couple of months ago, having never used a captcha before.  The good news is that it's very easy to do. 

  1. First, go and sign up for ReCaptcha, and download the dll.
  2. Place the Recaptcha.dll in the lib directory of your solution folder, and add a reference to it in your MVC projec.
  3. Make two folders in your MVC project - "ActionFilters" and "Helpers"
  4. Put this file in your Helpers folder - HtmlExtensions.cs.txt (624.00 bytes)
  5. Put this file in your ActionFilters folder - CaptchaValidatorAttribute.cs.txt (1.18 kb)

Remember that you have to have the [CaptchaValidator] attribute on the action that handles the Post:

[CaptchaValidator]
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Contact(FormCollection collection, bool captchaValid)
{
    //Code here
    return View("Index");
}


And finally, in the view where you wish the captcha control to appear: 

<%=Html.GenerateCaptcha()%>

And that's it!  Happy recapcha-ing all your spam. 

Tags: , ,
Categories: ASP.NET | C# | MVC