Creating Captcha Code in ASP.NET

Before proceeding with the topic first we must understand "What is a Captcha code?" and "Why do we use them?". Most web sites have a Captcha validation in their sites.

What is the Captcha code?

A Captcha code is simply a combination of some characters and numbers like "Alk13" or "aTu2eP" etc.

Why do we use them?

We use them for validating that the client browser window really has a human typing into it.

Ok, let's get to the topic i.e. creating your own Captcha code in ASP.Net.

Step 1

Go to Visual Studio and create a new project (web site or web application) say "CaptchCode".

Step 2

Now add a new page into your application say "ShowCaptcha.aspx" and add this code into the source for the page:

<div>

<table>

  <tr>

    <td>

      <asp:Image ID="imgCaptcha" runat="server" ImageUrl="~/CreateCaptcha.aspx?New=1"/>

     </td>

   </tr>

   <tr>

    <td>

      <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>

     </td>

    </tr>

    <tr>

     <td>

       <asp:Label ID="lblMessage" runat="server"></asp:Label>

      </td>

     </tr>

     <tr>

      <td>

 <asp:Button ID="btnCaptcha" runat="server" Text="Validate Cpatcha Code"                               onclick="btnCaptcha_Click" />

       </td>

       </tr>

     </table>

    </div>

Note: Here I am given the ImageUrl="~/CreateCaptcha.aspx?New=1" of the image control. In CreateCaptcha.aspx we will write the code for creating the Captcha code.

Step 3

Now add a new page into your application "CreateCaptcha.aspx" and create the following methods in its .cs file:

  /// <summary>

/// method for create captcha image

/// </summary>

 private void CreateCaptchaImage()

 code = GetRandomText();

 Bitmap bitmap = new Bitmap(200, 60, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

 Graphics g = Graphics.FromImage(bitmap);

 Pen pen = new Pen(Color.Yellow);

 Rectangle rect = new Rectangle(0, 0, 200, 60);

 SolidBrush blue = new SolidBrush(Color.CornflowerBlue);

 SolidBrush black = new SolidBrush(Color.Black);

 int counter = 0;

 g.DrawRectangle(pen, rect);

 g.FillRectangle(blue, rect);

 

 for (int i = 0; i < code.Length; i++)

 {

    g.DrawString(code[i].ToString(), new Font("Tahoma", 10 + rand.Next(15, 20), FontStyle.Italic), black, new PointF(10 + counter, 10));

   counter += 28;

 }

 DrawRandomLines(g);          

 bitmap.Save(Response.OutputStream, ImageFormat.Gif);

 g.Dispose();

 bitmap.Dispose();

 

}

 

/// <summary>

/// Method for drawing lines

/// </summary>

/// <param name="g"></param>

private void DrawRandomLines(Graphics g)

{

   SolidBrush yellow = new SolidBrush(Color.Yellow);

   for (int i = 0; i < 20; i++)

   {g.DrawLines(new Pen(yellow, 1), GetRandomPoints());}

 

}

 

/// <summary>

/// method for gettting random point position

/// </summary>

/// <returns></returns>

private Point[] GetRandomPoints()

{

  Point[] points = { new Point(rand.Next(0, 150), rand.Next(1, 150)), new    Point(rand.Next(0, 200), rand.Next(1, 190)) };

  return points;

}

  

/// <summary>

/// Method for generating random text of 5 cahrecters as captcha code

/// </summary>

/// <returns></returns>

private string GetRandomText()

{

  StringBuilder randomText = new StringBuilder();          

  string alphabets = "012345679ACEFGHKLMNPRSWXZabcdefghijkhlmnopqrstuvwxyz";

  Random r = new Random();

  for (int j = 0; j <= 5; j++)

  {randomText.Append(alphabets[r.Next(alphabets.Length)]);}

    Session["CaptchaCode"] = randomText.ToString();

     return Session["CaptchaCode"] as String;

  }

Step 4

To validate the Captcha code in the "ShowCaptcha.aspx.cs" page:
 

protected void btnCaptcha_Click(object sender, EventArgs e)

{

   //imgCaptcha.ImageUrl = "~/CreateCaptcha.aspx?New=0";

  if (Session["CaptchaCode"] != null && txtCaptcha.Text == Session["CaptchaCode"].ToString())

  {

     lblMessage.ForeColor = Color.Green;

     lblMessage.Text = "Captcha code validated successfully!!";

  }

  else

  {

   lblMessage.ForeColor = Color.Red;

   lblMessage.Text = "Captcha code is wrong!!";

  }

}

I hope this article will be helpful for you.

Happy Coding!!

Up Next
    Ebook Download
    View all
    Learn
    View all