Click here to Skip to main content
11,924,800 members (54,924 online)
Click here to Skip to main content
Add your own
alternative version


46 bookmarked

Creating CAPTCHA-Like Functionality in ASP.NET

, 8 Dec 2006
Rate this:
Please Sign up or sign in to vote.
How to create CAPTCHA-like functionality in ASP.NET.


According to Wikipedia, CAPTCHA ("Completely Automated Public Turing test to tell Computers and Humans Apart") is a challenge response test which is used to check if the user is human or not. CAPTCHA is used exclusively in applications where user input is required. These applications include blogs, forums, and portals. In this article, I will demonstrate how to create a simple webpage that uses the CAPTCHA functionality.

The CreateImage Method

The first task is to create an image and put it on the screen. For that, I have created an ASP.NET page named CaptchaControl.aspx. The CaptchaControl.aspx page will be responsible for displaying the image to the user. Let’s take a look at the following code which generates the image:

private void CreateImage()

    string code = GetRandomText();
    Bitmap bitmap = new Bitmap(200,150,
    Graphics g = Graphics.FromImage(bitmap);
    Pen pen = new Pen(Color.Yellow);
    Rectangle rect = new Rectangle(0,0,200,150);
    SolidBrush b = new SolidBrush(Color.DarkKhaki);
    SolidBrush blue = new SolidBrush(Color.Blue);
    int counter = 0;
    g.DrawRectangle(pen, rect);
    g.FillRectangle(b, rect);

    for (int i = 0; i < code.Length; i++)
           new Font("Verdena", 10 + rand.Next(14, 18)), 
           blue, new PointF(10 + counter, 10));
        counter += 20;

    Response.ContentType = "image/gif";


There is a bunch of stuff going on inside the CreateImage method. The GetRandomText method generates the random text and returns to the caller. If you are unfamiliar with creating random strings, then I would suggest that you check out my article: Creating Random Passwords. After I create the Rectangle where the text would appear, I resize the text to give it a strange look. Finally, I call the DrawRandomLines method which protects the image from OCR software.

The GetRandomText Method

The purpose of the GetRandomText method is to generate a random text every time a user gets the old text wrong. Take a look at the simple method which returns the random text.

private string GetRandomText()

    StringBuilder randomText = new StringBuilder();

    if (Session["Code"] == null)

        string alphabets = "abcdefghijklmnopqrstuvwxyz";
        Random r = new Random();

        for (int j = 0; j <= 5; j++)
        Session["Code"] = randomText.ToString();
    return Session["Code"] as String;

The DrawRandomLines Method

The DrawRandomLines method puts the lines on the text which is displayed on an image. The purpose of these lines is to make it difficult for the bots to read the text. This way the text can only be read by humans.

private void DrawRandomLines(Graphics g)
    SolidBrush green = new SolidBrush(Color.Green);

    for (int i = 0; i < 20; i++)
        g.DrawLines(new Pen(green, 2), GetRandomPoints());


private Point[] GetRandomPoints()

    Point[] points = { new Point(rand.Next(10, 150), 
                       rand.Next(10, 150)), 
                       new Point(rand.Next(10, 100), 
                       rand.Next(10, 100)) };
    return points;

Using the CAPTCHA Page

We have created the CAPTCHA feature, but the question is how do we use it. In order to use the CAPTCHA feature, you will need to create a page which consumes the CaptchaControl.aspx page. I have created the Default.aspx page which uses the CaptchaControl.aspx as the ImageUrl to the ASP.NET Image control. Check out the complete HTML code of the Default.aspx page.

<form id="form1" runat="server">
<asp:Image ID="myImage" runat="server" 
     ImageUrl="~/CaptchaControl.aspx" />
<br />
<br />
Enter code: <asp:TextBox ID="TextBox1" runat="server">
<asp:Button ID="Button1" runat="server" 
     Text="Validate" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="lblError" runat="server" Font-Bold="True" 
     Font-Size="X-Large" ForeColor="Red"></asp:Label></div>

The important thing to note is the ASP.NET Image control which requests the CaptchaControl.aspx page and generates the image. The code for the validation of the user text against the CAPTCHA text is pretty simple, and you can view it in the downloaded files.

Below is an image of how the application looks like:


In this article, I demonstrated how easy it is to create a CAPTCHA feature. This feature can play a very important role in the security of a web application.

I hope you liked the article, happy programming!


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
United States United States
I am the founder of knowledge base website, HighOnCoding, GridViewGuy, and

HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.

My Blog:


Buy my iPhone app ABC Pop

You may also be interested in...

Comments and Discussions

Questionsimple captcha Pin
shanid36014-Jun-12 20:34
membershanid36014-Jun-12 20:34 
GeneralHello Sir Pin
Saurabh Chandak20-Aug-10 1:23
memberSaurabh Chandak20-Aug-10 1:23 
QuestionIs there a ASP.NET VB version floating around? Pin
projecthiphop27-Jun-07 14:33
memberprojecthiphop27-Jun-07 14:33 
GeneralThank you Pin
cykophysh3925-Feb-07 4:59
membercykophysh3925-Feb-07 4:59 
GeneralEnhancement Pin
jcvest26-Dec-06 9:06
memberjcvest26-Dec-06 9:06 
GeneralRe: Enhancement Pin
cykophysh3925-Feb-07 4:53
membercykophysh3925-Feb-07 4:53 
GeneralA good start for a captiva, but as coded can easily be broken Pin
rweil12-Dec-06 13:33
memberrweil12-Dec-06 13:33 

The given code is a good start for a captcha, but as coded can easily be broken.

The problems that make it easy for a bot to overcome are:

1) The text, lines, backgound are all one solid color. This makes it is easy to seperate into three layers via a program. One should use a a patterned color.

2) The text is all a standard shape font. Any good OCR progam can learn the font quickly. The letters should should be warped in a random fashion.

3) The lines should be the same color as the text, so an edge matching algoritim can not detect the lines from the text. Humans, however, can do that resonable well.

4) The text is all horizontal. Again making it easy for a OCR program to learn. Placing the text on a curve would give more patterns for the OCR to learn.

This is a good start, but creating good captcha is hard. see

You can read more about captchas in the ACM article

An article with lots of samples at

Better code for creating captchas can be found at

One needs to be careful about a false sense of security as mentioned in

Roy W
GeneralRe: A good start for a captiva, but as coded can easily be broken Pin
azamsharp12-Dec-06 13:37
memberazamsharp12-Dec-06 13:37 
GeneralRe: A good start for a captiva, but as coded can easily be broken Pin
cykophysh3925-Feb-07 4:57
membercykophysh3925-Feb-07 4:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151125.3 | Last Updated 8 Dec 2006
Article Copyright 2006 by azamsharp
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid