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.
|