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.
- Variables are:
- Random r = new Random();
- string s = "";
- for (int j = 0; j < 5; j++)
- {
- //Code for creation
- }
Lower case
- ch = r.Next(0, 26);
- s = s + (char)('a' + ch);
- ch = r.Next(0, 26);
- s = s + (char)('A' + ch);
- ch = r.Next(0, 9);
- s = s + (char)('1' + ch);
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.
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.

karthick harderPosted Mar 18, 2016, 1:52 AM
Nice one
Aappasaheb TawalePosted Sep 18, 2015, 6:22 AM
Really Good
Humayun Kabir MamunPosted Sep 11, 2015, 1:48 AM
Nice...
Sibeesh VenuPosted Sep 10, 2015, 8:09 AM
Nice Share
Rajeesh MenothPosted Sep 10, 2015, 1:08 AM
Good One..
Baimey RajeshPosted Sep 10, 2015, 1:07 AM
Thanks for the encouragement :) Please put in queries as well. So I can help me there by help myself :)
Ankit BansalPosted Sep 10, 2015, 1:03 AM
good one..thanks...
Pankaj Kumar ChoudharyPosted Sep 9, 2015, 9:36 PM
Nice Article Mam......
Santhakumar MunuswamyPosted Sep 9, 2015, 3:20 PM
Thanks for nice article
Mohammed IbrahimPosted Sep 9, 2015, 2:04 PM
nice share
RakeshPosted Sep 9, 2015, 12:04 PM
Nice one
Shridhar SharmaPosted Sep 9, 2015, 10:57 AM
it's cool.
Karthikeyan KPosted Sep 9, 2015, 9:40 AM
Good one mam...Thanks for sharing
Nilesh JadavPosted Sep 9, 2015, 9:34 AM
Nice article mam