How to implement Captcha in Asp.net

Asp.net Captcha. In this post I will create simple CAPTCHA image using ASP.Net with C#.net and VB.net. CAPTCHA is used to identify end user as a human. Many websites are using captcha technique to identify humans. Let's see how to implement captcha in Asp.net and how Captcha works with session and text string challenge.

This article will help you to convert String to Image or Convert Text to image

Idea is, system will store randomly generated text into session. later the text would be rendered as an image (Convert text to image.)

The working copy can be downloaded from here.captcha.rar (2.44 kb)

Implement Captcha in Asp.net.

Aspx Page.

<form id="form1" runat="server">
       <div>
           <img src="Handler.ashx" />
           <br />
           Please type above text here. To identify your self as a human
           <br />
           <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
           <br />
           <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
           <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
   </form>


In above code, the image tag <img src="Handler.ashx" /> requests  Http Handler.

Let’s add Generic handler to your new asp.net project. IE or FF end user browser will request this handler code when it reaches to above image tag.

<%@ WebHandler Language="C#" Class="Handler" %>

using System; 
using System.Web; 
using System.Web.SessionState; 
using System.Drawing; 
using System.Drawing.Imaging; 

public class Handler : IHttpHandler,IRequiresSessionState 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
        using (Bitmap b = new Bitmap(250, 50)) 
        { 
            Font f = new Font("Arial", 10F); 
            Graphics g = Graphics.FromImage(b); 
            SolidBrush whiteBrush = new SolidBrush(Color.Blue); 
            SolidBrush blackBrush = new SolidBrush(Color.White); 
            RectangleF canvas = new RectangleF(0, 0, 250, 50); 
            g.FillRectangle(whiteBrush, canvas);            
            context.Session["Captcha"] = GetRandomString(); 
            g.DrawString(context.Session["Captcha"].ToString(), f, blackBrush, canvas); 
            context.Response.ContentType = "image/gif"; 
            b.Save(context.Response.OutputStream, ImageFormat.Gif); 
        } 
    } 
    
    public bool IsReusable 
    { 
        get 
        { 
            return false; 
        } 
    } 
    
    private string GetRandomString() 
    { 
        string []arrStr = "A,B,C,D,1,2,3,4,5,6,7,8,9,0".Split(",".ToCharArray()); 
        string strDraw = string.Empty; 
        Random r = new Random();         
         for(int i = 0; i < 5 ; i++) 
         { 
              strDraw += arrStr[r.Next(0,arrStr.Length-1)]; 
         }        
        return strDraw; 
    } 
} 

Now, open your Default.aspx page code behind where we have added Captcha image tag.

On button click validate whether user has entered correct text that is rendered by system or not.

protected void Button1_Click(object sender, EventArgs e)
 {
   if (Session["Captcha"].ToString() == TextBox1.Text)
   {
     Label1.Text = " System identified you as a human";
   }
   else
   {
     Label1.Text = "Please try again";
     TextBox1.Text = "";
   }
 } 

 

Description: When browser request the captcha image, the captcha image handler sends auto generated text image to browser. It’s challenging for software to read text written inside image. The same text we are storing it in Session. We compare the text submitted by end user with value stored in side the text. This means human has read the text and submitted back to the server. As text written on image is inside the session we can compare and validate human is visiting or posting the data.

This is very useful and important technique to stop auto bots or crawler or machine feeds.

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.