Creating a Simple Captcha Image for an MVC Application

by Graeme

The following is a walkthrough to create a simple captcha image to use in your MVC application, for the purpose of say verifying blog comments are coming from a human source.  Which is purely the reason I created mine, I was sick of getting spam comments on the posts and using a Captcha is the quickest way to prevent the deluge of automated spam responses.

1. The first step is to create an ImageResult MVC ActionResult (if your application hasn't had need of one already).  This is a simple class that inherits from the standard ActionResult but instead of streaming a html response, streams the binary of your image. Your action code may look something like this:

2. Once you have the ImageResult it becomes very simple to return any image you create (or load from elsewhere e.g. from disk) as the result of a controller action.  You can construct a very basic bitmap image, containing your captcha word and return it to the user with some code like the following:

Nb. I also take the simplistic approach to storing the captcha string of simply putting this in the session.  To be safer (in case of a user having multiple pages open simulteanously) I should have had the captcha value stored against a request key and embed the request key into the view page, so it was available on post back.

3. Now all you have to do us make sure on the viewpage to have an image thats url points to the controller action

4. Lastly check that the user has entered the correct string of characters before allowing your post action to continue.

There you have it a simple Captcha system that you can use inside an Asp.Net MVC application.  My image for the captcha is very basic but you can improve this by any of the drawing functions to help make it harder for a non-human to parse the text for themselves, such as making the text wavy, fuzzy adding grid lines over the top etc.


Posted at 5/26/2010 9:26:50 PM | Comments (2)
This is so wrong! - you leak resources - MemoryStream is disposable, Bitmap is disposable and IIRC Graphics is also disposable - you store captcha value in the session which means last image wins - in case of multiple captchas (think e.g. browser tabs) it will all break
By x at 6/18/2010 4:36:15 AM
Just to preface I did say that this was just a simple solution. That said your points are all valid, to be more robust and defensive the MemoryStream and Graphics should be wrapped into usings, and the Image explicitly disposed. As for the storing in the session it can be extended so that you store in a dictionary keyed against a unique page id, this will allow to correlate to the correct tab etc.
By Graeme at 7/12/2010 9:28:43 PM
Submit a Comment:


© 2010 Graeme Finn