Creating Captcha For ASP.NET Forms

Nowadays technology is to be checked and rechecked to confirm to be good. Even a form submission is spammed by users. To prevent this spamming we have come up with Captcha.

There is a large number of ways to create captcha in ASP.NET. I have tried different ways and found the following solution developer friendly and reusable.

What is a Captcha

A CAPTCHA is an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart". This proves the user to be human.

Approach

In this approach, we have an ASPX file that output the captcha. This page output is an image.
To use this .aspx file, we can simply make this page as the source of an image tag. Each refresh of the image reloads the captcha with new images.

According to the requirement, the captcha can contain upper case, lower case, numbers and special characters. Let’s now see the details of implementation.

Implementation

Random.cs is the key class that creates the image. This class has a constructor that takes the image text, width and height.

There are two other methods:

  • For setting dimensions
  • For generating Image

In the Captcha.aspx. page, a random string is created.

  1. Variables are:  
  2. Random r = new Random();  
  3. string s = ""
Loop as per the length required
  1. for (int j = 0; j < 5; j++)  
  2. {  
  3.    //Code for creation  
  4. }  
According to the criteria specified the function can be different

Lower case
  1. ch = r.Next(0, 26);  
  2. s = s + (char)('a' + ch); 
Upper Case
  1. ch = r.Next(0, 26);  
  2. s = s + (char)('A' + ch);  
Number
  1. ch = r.Next(0, 9);  
  2. s = s + (char)('1' + ch);
After creating the string, value is added to a session or cookie. This is passed to the random image class constructor with the required width and height.

The response of the page is made an image.

// Change the response headers to output a PNG image.
this.Response.Clear();
this.Response.ContentType = "image/png";


The captcha image is added to the page by referring to as the image url for the image tag.
For refreshing just rebind the url with JavaScript.

Conclusion

I have attached an image of the captcha usage.
A simple sample page that can guide through, is also available for download.

NB: When the url is bind to the image tag, some browsers have an issue with refresh. To avoid this add a query string parameter and this can be the current data and time, so the url becomes unique and the image always updates.
 
In javascript; for refresh 
                           var d = new Date();
                           $("#img1").attr("src", "CImage.aspx?" + d.getTime());
 


Similar Articles