ASP.NET MVC Preview 2 CAPTCHA using ActionFilterAttribute

My last article on ASP.NET MVC CAPTCHA was very well received by many of my readers and it even caught the eye of the DotNetKicks crowd. Now that MVC Preview 2 was released last week, many new features make encapsulating my CAPTCHA control even easier. Most notably is the ActionFilterAttribute which allows you to override the Pre and Post action events for any action the attribute is applied to.

Basically everything works the same as it did in the previous article. I just modified things for MVC Preview 2. To validate the CAPTCHA you add the attribute CaptchaValidation to the action.

[CaptchaValidation("captcha")]  
public void Register(string userName, string password, string email, string question, string answer, bool captchaValid){  
    // do stuff
}

You still need to register the CAPTCHA image handler.

<httpHandlers>  
    <add verb="GET" path="captcha.ashx" validate="false" type="ManagedFusion.Web.Handlers.CaptchaImageHandler, ManagedFusion" />
</httpHandlers>

I added an extension to HtmlHelper that generates a text box with autocomplete="off".

<label for="captcha">Enter <%= Html.CaptchaImage(50, 180) %> Below</label><br />  
<%= Html.CaptchaTextBox("captcha") %>

Which generates the following.

Example of CAPTCHA

You can view the source code for this on my Google Code Project, everything is available through SVN.

  1. CaptchaValidationAttribute.cs
  2. CaptchaHelper.cs
  3. CaptchaImage.cs
  4. CaptchaImageHandler.cs

Or you can download the project for you own personal use.

Nick Berardi

In charge of Cloud Drive Desktop at @Amazon, Entrepreneur, Microsoft MVP, ASPInsider, co-founder and CTO of @CaddioApp, Father, and @SeriouslyOpen host