Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Using ReCaptcha with Asp.Net MVC

For all the debate regarding if Captcha's are a good thing or a bad thing one thing is certain (in my book).  If you do not have some way to stop spam-bots your site will become overridden with junk in a hurry.

In an effort to reduce the amount of spam comments I am getting over at Dimecasts.net I finally got off my lazy ass and worked on implementing a Captcha.  The solution I ended up going with was reCaptcha.  I found that their setup was very easy to use and worked right out of the box.  However, there was not a lot of information on the net on how to use reCaptcha within an MVC site, only Asp.Net Webforms.  So I thought I would share my experiences and explain how I implemented reCaptcha on Dimecasts.

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() %>:

Step 7 - Oh wait, there is no step 7.  You are done.

There you go, that is all that is needed to setup reCaptcha for use in a MVC application

Till next time,

[ --- Remember to check out Dimecasts.net --- ]


Posted 12-02-2008 8:09 AM by Derik Whittaker
Filed under: , ,

[Advertisement]

Comments

DotNetKicks.com wrote Using ReCaptcha with Asp.Net MVC
on 12-02-2008 9:12 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Nick wrote re: Using ReCaptcha with Asp.Net MVC
on 12-02-2008 10:52 AM

You might also want to look at Akismet.  It's used with WordPress, but many other blog engines also use it.  I've had a very high success rate with catching spam using it, and it doesn't necessitate punching in CAPTCHA codes.

Derik Whittaker wrote re: Using ReCaptcha with Asp.Net MVC
on 12-02-2008 11:32 AM

@Nick,

I looked at that, but Dimecasts is on the border of being 'commercial' in their eyes and i am not willing to pay for that service right now.

Dew Drop - December 3, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - December 3, 2008 | Alvin Ashcraft's Morning Dew
on 12-03-2008 9:33 AM

Pingback from  Dew Drop - December 3, 2008 | Alvin Ashcraft's Morning Dew

ASP.NET MVC Archived Blog Posts, Page 1 wrote ASP.NET MVC Archived Blog Posts, Page 1
on 12-04-2008 12:34 AM

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

Andrew wrote re: Using ReCaptcha with Asp.Net MVC
on 12-04-2008 9:36 AM

Have you tried this using Ajax to post the form? I'm wondering what it would take to pass the info from reCaptcha back to my controller when using jQuery.

Tuna Toksoz wrote re: Using ReCaptcha with Asp.Net MVC
on 12-08-2008 5:06 PM

How about using ModelState for invalid captcha,

filterContext.Controller.ViewData.ModelState.AddModelError()

I am planning to implement it this way, and blog about it (and you beat me to writing a blog post)

Cheers!

DotNetLinks.net wrote Using ReCaptcha with Asp.Net MVC
on 12-17-2008 1:52 PM

Track back from DotNetLinks.net

Integrating reCAPTCHA into a MonoRail project « Andy Pike wrote Integrating reCAPTCHA into a MonoRail project &laquo; Andy Pike
on 01-04-2009 4:54 PM

Pingback from  Integrating reCAPTCHA into a MonoRail project &laquo; Andy Pike

Kart Vijay wrote re: Using ReCaptcha with Asp.Net MVC
on 01-06-2009 3:31 PM

I tried adopting the above approach and for some reason the reCaptchaResponse.IsValid is always false and it gives the error code  "incorrect- captcha-sol" . I know the value i am entering is correct. Any thoughts?

Andre wrote re: Using ReCaptcha with Asp.Net MVC
on 02-19-2009 10:03 PM

Very helpful. Thanks.

Kazi Manzur Rashid's Blog wrote ASP.NET MVC Best Practices (Part 1)
on 04-01-2009 11:44 AM

In this post, I will share some of the best practices/guideline in developing ASP.NET MVC applications

Mario wrote re: Using ReCaptcha with Asp.Net MVC
on 04-21-2009 1:26 PM

I'm still not sure if I should use Akismet vs reCaptcha

Simeon wrote re: Using ReCaptcha with Asp.Net MVC
on 04-24-2009 3:08 AM

Wow!, thank you so much, I had been trying to make this work with my latest MVC website and I had almost given up, then I found your article. I am amazed how I could just copy and paste your code and it worked!! This is definitely something to bookmark :)

Thank Again!

David Hollins wrote re: Using ReCaptcha with Asp.Net MVC
on 05-14-2009 2:21 PM

Excellent implementation!  Thanks a ton!  Worked like a champ!

Gopinath wrote re: Using ReCaptcha with Asp.Net MVC
on 07-25-2009 4:59 AM

You are a genius. MVC Maverick!!

Thanks a ton for the code.

Richard Moss wrote re: Using ReCaptcha with Asp.Net MVC
on 07-27-2009 3:50 PM

Excellent! Sadly I couldn't get Nick Berardi's solution to work, however this one went in like a charm... thanks for sharing.

paul mungai wrote re: Using ReCaptcha with Asp.Net MVC
on 07-31-2009 4:40 AM

Great post!

I'm using it already.

Thanks.

parapapat wrote re: Using ReCaptcha with Asp.Net MVC
on 08-06-2009 2:45 AM

Hi! Very usefull!! But I need to change Recaptcha options... How can I do that?

Thank you very much!!

TrackBack wrote Recatcha In MVC
on 08-21-2009 7:28 PM

Recatcha In MVC

TrackBack wrote re: Using ReCaptcha with Asp.Net MVC
on 08-26-2009 3:53 AM

Very useful thanks!

TrackBack wrote Recaptcha In MVC
on 08-26-2009 1:04 PM

Recaptcha In MVC

Mustafa wrote re: Using ReCaptcha with Asp.Net MVC
on 10-13-2009 3:50 PM

Sorry to be a drag, but I'm having trouble getting it to work. I can see that my "GenerateCaptcha" method is called and outputs what appears to be valid html/javascript, but when I include it in my view, I can briefly see my view being rendered and then the page is automatically redirected to a blank screen and my browser's status bar says "Read api.recaptcha.net".

Any ideas?

Robert Claypool wrote re: Using ReCaptcha with Asp.Net MVC
on 10-30-2009 2:55 PM

Thanks for the great code! I've added localization with the following:

/// <summary>

/// Languages that ReCaptcha currently supports.

/// </summary>

/// <see cref="recaptcha.net/.../>

private static List<string> RECAPTCHA_LANGUAGES = new List<string>() { "en", "nl", "fr", "de", "pt", "ru", "es", "tr" };

public static string GenerateReCaptcha(this HtmlHelper helper)

{

var captchaControl = new RecaptchaControl

{

ID = "recaptcha",

Theme = "blackglass",

PublicKey = "000000000000",

PrivateKey = "000000000000"

};

var htmlWriter = new HtmlTextWriter(new StringWriter());

captchaControl.RenderControl(htmlWriter);

var html = htmlWriter.InnerWriter.ToString();

// Take the html that the ReCaptcha.dll generates and add support for localization.

string localizedHtml;

var culture = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower();

if (RECAPTCHA_LANGUAGES.Contains(culture))

{

localizedHtml = html.Replace("RecaptchaOptions = {", "RecaptchaOptions = { lang : '" + culture + "',");

}

else

{

// ReCaptcha defaults to english.

localizedHtml = html;

}

return localizedHtml;

}

uberVU - social comments wrote Social comments and analytics for this post
on 12-07-2009 9:00 AM

This post was mentioned on Twitter by karlseguin: @DerikWhittaker thanks for http://is.gd/1O3c6 its proving helpful

Develop.Net() wrote Using Captcha with Asp.Net MVC
on 04-29-2010 12:16 PM

Using Captcha with Asp.Net MVC

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)