Since my last release of the MVC toolkit some major changes have taken place in the MVC Framework. I am going to do a quick run through of how they changed the MVC CAPTCHA for the better.
Originally in MVC Preview Release 1 for the MVC CAPTCHA many of you remember that the indicator for a valid CAPTCHA was passed through the parameters of the action method like so:
[ControllerAction]
[CaptchaValidation("captcha")]
public void Register(bool captchaValid, string otherParameters)
{
// do stuff
}
However when Preview Release 2 came out the ability to pass the parameter through the action method was broken. So I had to create a hack around this:
[CaptchaValidation("captcha")]
public void Register(string otherParameters)
{
bool captchaValid = (bool)RouteData.Values["captchaValid"];
// do stuff
}
Apparently without realizing it in Preview Release 1, I had discovered a major feature that everybody that I explained it to saw great potential in. So I submitted a feature request and waited for the ASP.NET Team to get back to me. With the release of Preview Release 3, they finally answered my prayers and added the parameter injection feature back in to the framework.
So now this code works again in the Preview Release 3 version of the MVC CAPTCHA control.
[CaptchaValidation("captcha")]
public void Register(bool captchaValid, string otherParameters)
{
// do stuff
}
This works because of a new property called ActionParameterson the ActionExecutingContext. It can be used to test and change any of the action methods parameters before the action method has been executed. For the purpose of the MVC CAPTCHA control it allows me to inject a true or false value in to a parameter called captchaValid, so that the action method knows that the CAPTCHA validation passed or failed.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// make sure no values are getting sent in from the outside
if (filterContext.ActionParameters.ContainsKey("captchaValid"))
filterContext.ActionParameters["captchaValid"] = null;
// get the guid from the post back
string guid = filterContext.HttpContext.Request.Form["captcha-guid"];
// check for the guid because it is required from the rest of the opperation
if (String.IsNullOrEmpty(guid))
{
filterContext.RouteData.Values.Add("captchaValid", false);
return;
}
// get values
CaptchaImage image = CaptchaImage.GetCachedCaptcha(guid);
string actualValue = filterContext.HttpContext.Request.Form[Field];
string expectedValue = image == null ? String.Empty : image.Text;
// removes the captch from cache so it cannot be used again
filterContext.HttpContext.Cache.Remove(guid);
// validate the captch
filterContext.ActionParameters["captchaValid"] =
!String.IsNullOrEmpty(actualValue)
&& !String.IsNullOrEmpty(expectedValue)
&& String.Equals(actualValue, expectedValue, StringComparison.OrdinalIgnoreCase);
}
Notice in the code above all the filterContext.ActionParameters references, that is the CAPTCHA validation checking for the parameter in the method parameters list and adding the value of the CATPCHA validation to the list. Note that in order for this to work you must already have the captchaValid attribute present in your method, these actions merely fill in the value of the captchaValid placeholder.
For anybody who hasn’t used my MVC CAPTCHA control before, you only need to do two things:
1. You need to register the CAPTCHA image handler.
<httpHandlers>
<add verb="GET" path="captcha.ashx" validate="false" type="ManagedFusion.Web.Handlers.CaptchaImageHandler, ManagedFusion" />
</httpHandlers>
2. Add the following to the View that you want the CAPTCHA to show in. Note the extension, CaptchaTextBox in HtmlHelper, generates a text box with autocomplete=”off” so that the CAPTCHA box will not have an auto-complete show up.
<label for="captcha">Enter <%= Html.CaptchaImage(50, 180) %> Below</label><br />
<%= Html.CaptchaTextBox("captcha") %>
Which generates the following.
If you would like to download the latest copy of the MVC CAPTCHA it is available in my MVC Toolkit.
Download: Coder Journal MVC Toolkit
Source: Coder Journal MVC Toolkit



Nick do you have a working web site with this?
I can not seem to make it work… I’m not sure if this is because I am using the MVC Membership Starter Kit or what…
But it doesn’t seem to want to spit out the image instead I get a error from the MVC assembly stating that it can’t find the controller for captcha.ashx
Please help..thanks
That is because you action is probably picking it up. put a constraint on your action and controller. to check for periods. “[^\\.]*” works really well.
Thanks Nick
I actually did get it to work …well at least to display
now I get this
A value is required for parameter ‘captchaValid’ in action ‘Register’. The parameter either has no value or its value could not be converted. To make a parameter optional its type should either be a reference type or a Nullable type.
I gather it has something to do with the OnActionExecuting filter thingy… where in tarnation do I place that code in my project?
Actually got it working
You have to declare the captchaValid as a nullable parameter like so
[CaptchaValidation("captcha")]
public void Register(bool? captchaValid, string otherParameters)
{
// do stuff
}
also in the web config make sure to declare it like this
Not the dot Mvc
whats listed in the blog post must be dated.. and was changed at some point.
hmm either I forgot or it got cut off
Thanks for the great work, this is very helpful. I recently used this and made some modifications you might find useful including:
1) Modifying CaptchaTextBox to allow for custom html attributes (such as defining the CSS class)
2) Modifying CaptchaValidationAttribute to automatically invalidate my model (instead of set a captchaValid value)
Details are at http://noahblu.wordpress.com/2008/10/28/aspnet-mvc-captcha/
Noah
Hi,
I’m trying this captcha module into my ASP.NET MVC (beta) application, but I can’t get it to work. I think it has to do with the beta release of MVC. I get the error CaptchaImage is not a member of System.Web.Mvc.HtmlHelper.
Do I need to modify anything?
Thanks in advance
Nick,
Thanks for your reply in your mail, it’s working now. I had some problems with implementing it in vb.net.
I’m trying to use IIS 5.1 (XP) and 6.0 (so I’m using the .mvc extension for my controllers) but I can’t get the captch image to display. The exception generated is:
System.Web.HttpException: The incoming request does not match any route.
at System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContextBase httpContext)
at System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContext httpContext)
at System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
This is my route table setup:
// For IIS 5.1 (XP)
routes.MapRoute(
“Default2″, // Route name
“{controller}.mvc/{action}/{id}”, // URL with parameters
new { controller = “Home”, action = “Home”, id = “” }, // Parameter defaults
new { action = “[^\\.]*” }
);
routes.MapRoute(
“Default”, // Route name
“{controller}/{action}/{id}”, // URL with parameters
new { controller = “Home”, action = “Home”, id = “” }, // Parameter defaults
new { action = “[^\\.]*” }
);
The request generated is this (e.g.):
http://localhost/Member.mvc/captcha.ashx?guid=adf8d220cedd441daf55a5c0c688dfc4
This works great when I run it through the VS.Net 2008 web server, but not IIS 5.1/6. What am I missing?
Thanks,
Chris
Hi I am using Asp.Net MVC 1.0
i tried to use this captcha control but it doesn’t work
i tried it into a usercontrol
it shows me this error
error CS0012: The type ‘System.Web.Mvc.HtmlHelper’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’.
Kind Regards,
Saurabh
I’m having some issues running this component on a web farm. the cache object is not getting propagated to the farm and component fails to verify/generate the image.
Please advise,
Thanks,
Ehsan
Just wanted to say thanks for an excellent component. We are currently using in one of our projects. I did have to make one tiny modification, which seems to be related to many of the problems others are also having. It was just too much of a pain to stop it matching some of our routes, particularly a catch all route which is our last route. Rather than put route constraints on the few routes I decided it was easier to put a / at the front of the captcha img src value in your html helper. This means that you can stop any routes matching the handler with ‘routes.IgnoreRoute(“{handler}.ashx”)’ in your route setup.
Once again great work and thanks for sharing!