Thursday, October 14, 2010

Adding reCAPTCHA to MVC

These are just a few steps, as the latest reCAPTCHA library has all the pieces you need for MVC:

  • Go to Get reCAPTCHA, which gives you the public and private keys you need to use reCAPTCHA with your site
  • Download the latest .net library at: Currently: dotnet-
  • Add <%= Html.GenerateCaptcha()%> to the form you want to protect with the reCAPTCHA. Naturally you have to add the namespace for the extension to be recognized, some of the options:
    • Add the namespace to the web.config:
      <add namespace="Recaptcha" />

    • Add the namespace at the view:

      <%@ Import Namespace="Recaptcha" %>

    • Add your own extension method that wraps it. I changed the signature to return MvcHtmlString to prevent double encoding when using it with “<%:” instead of “<%=”

      public static MvcHtmlString GenerateCaptcha(this HtmlHelper htmlHelper)
      var html = Recaptcha.RecaptchaControlMvc.GenerateCaptcha(htmlHelper);
      return MvcHtmlString.Create(html);

  • Add the RecaptchaControlMvc.CaptchaValidator attribute to your controller. Also add parameters named captchaIsValid and captchaErrorMessage. Just like:

    public ActionResult MyMethod(Something else, bool captchaValid, string captchaErrorMessage)
    // do something if (!captchaValid)

  • Configure your keys. Some options:

    • Add to appsettings in the web.config, with entries named: RecaptchaPublicKey and RecaptchaPrivateKey
    • Set at Application Start:

      RecaptchaControlMvc.PrivateKey = privKey;
      RecaptchaControlMvc.PublicKey = pubKey;


  1. why would you want to add that crap to your site? especially recaptcha

  2. While I usually take a more preventive approach, in this particular case it wasn't in place and we were already being hit by account creation bots.

    It's not a situation you want to have. It solves a very specific problem, preventing or at least strongly discouraging automated submissions.

    As for why reCAPTCHA, it's very well known and works well. I'd love to see some serious CAPTCHA comparisons, but don't bother including any CAPTCHA that's not accessible to blind users.