Using Captcha with Asp.Net MVC

 A while ago I was implementing Captcha into the MVC. I had always used ReCaptcha as it is full featured, and they are doing something positive by using the results of the answers to help translate old documents and books. Quite cool really.

Anyway I had always done this in the more traditional coding way (dragging a component onto the form, then handling in postback).  However I thought that there would have to be a better way using ActionFilterAttributes to handle the teadious part for me.  Luckily a quick search on the internet found this: http://devlicio.us/blogs/derik_whittaker/archive/2008/12/02/using-recaptcha-with-asp-net-mvc.aspx (reposted below incase link goes down).

Step 1 - Signup for and download the reCaptcha dll from their site

Step 2 - Add reference to the Recaptcha.dll to your project

Step 3 - Create an Action Filter to handle the Captcha validation

public class CaptchaValidatorAttribute : ActionFilterAttribute    
{   
    private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";   
        private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";   
           
        public override void OnActionExecuting(ActionExecutingContext filterContext)   
        {   
            var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY];   
            var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY];   
            var captchaValidtor = new Recaptcha.RecaptchaValidator   
                                      {   
                                          PrivateKey = -- PUT PRIVATE KEY HERE --,   
                                          RemoteIP = filterContext.HttpContext.Request.UserHostAddress,   
                                          Challenge = captchaChallengeValue,   
                                          Response = captchaResponseValue   
                                      };   
  
            var recaptchaResponse = captchaValidtor.Validate();   
  
            // this will push the result value into a parameter in our Action   
            filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid;   
  
            base.OnActionExecuting(filterContext);   
        }   
}

Step 4 - Implement the Controller Action that will handle the form submission and Captcha validation.

[CaptchaValidator]   
[AcceptVerbs( HttpVerbs.Post )]   
public ActionResult CreateComment( Int32 id, bool captchaValid )   
{   
.. Do something here   
}

Step 5 - Create a Html Helper to build and render the Captcha control

public static string GenerateCaptcha( this HtmlHelper helper )   
{   
               
    var captchaControl = new Recaptcha.RecaptchaControl   
            {   
                    ID = "recaptcha",   
                    Theme = "blackglass",   
                PublicKey = -- Put Public Key Here --,   
                        PrivateKey = -- Put Private Key Here --   
        };   
  
    var htmlWriter = new HtmlTextWriter( new StringWriter() );   
  
    captchaControl.RenderControl(htmlWriter);   
  
    return htmlWriter.InnerWriter.ToString();   
}

Step 6 - Implement the logic in your view to actually render the Captcha control

<%= Html.GenerateCaptcha() %>

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About Me

I am 27year old living in London.  Director of Development for an online technology/marketing company - Intuitive Search Technologies.