Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Free Captcha Control

3.64/5 (10 votes)
9 Dec 2009CPOL2 min read 46.2K   3.4K  
Free Captcha Control
image1.png

image2.png

image3.png

Introduction 

The captcha control is a self contained Web control. It is easy to use and secure. It prevents automated registration.

Background

I was given a task to add a captcha validation on a registration page. I found an article in CodeProject that is right on the target. The article solved that task, but I wasn't very happy about having to have an ASPX page reference, a need for a session variable, not easily customizable, distorting the whole image instead of letter. I'm in my vacation and spending a night creating a control to share and for future references.

Using the Code

Add an assembly reference to the control on a page:

ASP.NET
<%@ Register Namespace="CaptchaControl" Assembly="CaptchaControl" TagPrefix="cc" />

Add the CaptchaControl tag to the page:

ASP.NET
<cc:CaptchaControl ID="captcha" runat="server"  
	CharCount="5" Width="200" CharSet="AllLowerCaseLetters"/>

On postback, call captcha.Validate(userinput) -- where userinput is what user typed.

The default values for the control are:

C#
public CaptchaControl()
{
    IgnoreCase = true;
    CharCount = 3;
    this.Width = new Unit(120);
    this.Height = new Unit(50);          
    Password = this.GetType().AssemblyQualifiedName;
    CharSet = CharSets.NumberAndLetters;
}

Known Issues

When two users or browser windows of the page are open, after a user (user1) input passes the validation and the other user refreshes the page, if user1 hits the submit button again with the input from the new image, the user will get "validation failed".

This is because the code in the viewstate does not match the code in the new image any more. This problem shouldn't be a problem in the real application because mostly we would want a page redirect to a different page on successful validation. This problem can be resolved if we append the image file name with a guid id, but this approach introduces a new problem that is having a lot of images being created.

Each character needs about 40px of space, if you increase the CharCount by 1, you should increase Width by 40 to prevent character image cutoffs.

Points of Interest

It was fun to add noise and distort the character bitmap image. This is one of the major advantage features over the article I read. Any cool way of distorting the image, please post it here, I'll add it to the project.

This control stores the encrypted code in the viewstate, the password can be set in the HTML markup or programmatically.

My next step on this subject is trying to create an HTML helper function for ASP.NET MVC. 

History

  • 9th December, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)