reCAPTCHA for ASP.NET MVC that uses ModelState

Here is a reCAPTCHA control for ASP.NET MVC that uses ModelState. This code includes the ActionFilter as well as the HTML Helper for rendering the reCAPTCHA control.

To use it, add the ActionFilter to the Controller Action that will be performing the verification. You can either provide the Private Key in the web.config or explicitly state it. You can also use the IgnoreOnMobile boolean property to ignore reCAPTCHA verification if a mobile browser is detected. You can also add a function delegate that returns a boolean value to the Ignore property to add custom logic to ignore reCAPTCHA under any condition you would like.

[Recaptcha.Mvc.RecaptchaFilter(PrivateKey = "my_private_key", IgnoreOnMobile=true)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Post post)
{
   if (!ModelState.IsValid)
   {
       // model state and recaptcha were valid, continue onwards!
   }
   else
   {
       // model state was not valid, redirect back to source page
   }
}

To render the reCAPTCHA control, simply add the Recaptcha.Mvc to the page and use the HtmlHelper.

<%@ Import Namespace="Recaptcha.Mvc" %>
...

<%= Html.CreateRecaptcha("recaptcha", "my_private_key", "my_public_key", "clean") %>

If you wish to set the private/public keys in the web.config you can set them in the appSettings section.

  <appSettings>
    <add key="RecaptchaPrivateKey" value="my_private_key"/>
    <add key="RecaptchaPublicKey" value="my_public_key"/>
  <appSettings>

The source code is attached below as a Solution and Project that needs to be built. Alternatively you can just add the csharp source files and drop them into your project appropriately.

AttachmentSize
Recaptcha.Mvc_.zip12.38 KB

Comments

#1 Anonymous

Where's the code?

#2 khuang

Sorry, apparently the drupal module for uploads got disabled somehow.

Recent comments