Generation of CAPTCHA Image Using Generic Handler for Login Page

This article explains how to create a CAPTCHA image using a generic handler.

Required Tools

  1. Visual Studio
  2. SQL Server 2005

Step 1

Create a new solution and add an empty web project.

Step 2

Add a generic handler page (.ashx).

generic handler

Step 3

Replace the ProcessRequest method implementation with the following code. 

  1. <%@ WebHandler Language="C#" Class="ghCaptcha" %>  
  2.   
  3. using System;  
  4. using System.Web;  
  5. using System.IO;  
  6. using System.Web.SessionState;  
  7. using System.Drawing;  
  8. using System.Drawing.Imaging;  
  9.   
  10. public class ghCaptcha : IHttpHandler, IReadOnlySessionState  
  11. {  
  12.     public void ProcessRequest(HttpContext context)  
  13.     {  
  14.         MemoryStream memStream = new MemoryStream();  
  15.         string phrase = Convert.ToString(context.Session["Captcha"]);  
  16.   
  17.         //Generate an image from the text stored in session  
  18.         Bitmap CaptchaImg = new Bitmap(180, 60);  
  19.         Graphics Graphic = Graphics.FromImage(CaptchaImg);  
  20.         Graphic.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;  
  21.   
  22.         //Set height and width of captcha image  
  23.         Graphic.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 180, 60);  
  24.         Graphic.DrawString(phrase, new Font("Calibri", 30), new SolidBrush(Color.White), 15, 15);  
  25.         CaptchaImg.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);  
  26.         byte[] imgBytes = memStream.GetBuffer();  
  27.   
  28.         Graphic.Dispose();  
  29.         CaptchaImg.Dispose();  
  30.         memStream.Close();  
  31.   
  32.         //write image  
  33.         context.Response.ContentType = "image/jpeg";  
  34.         context.Response.BinaryWrite(imgBytes);  
  35.     }  
  36.   
  37.     public bool IsReusable  
  38.     {  
  39.         get  
  40.         {  
  41.             return false;  
  42.         }  
  43.     }  
  44. }  

Step 4

Build the page and resolve the namespace.

Since the .ashx is a generic handler it process HTTP requests and doesn't write session values. So we need to inherit the class with IReadOnlySessionState as in the following:

inherit class

The following namespaces are used:

  1. using System;  
  2. using System.Web;  
  3. using System.IO;  
  4. using System.Web.SessionState;  
  5. using System.Drawing;  
  6. using System.Drawing.Imaging;  

Step 5

Prepare the Login page; add a new page named Login.aspx and add the following .aspx script: 

  1. <form id="form1" runat="server">  
  2.     <h1>  
  3.         Login</h1>  
  4.     <table id="tblLogin" width="40%" border="0" cellpadding="0" cellspacing="4" style="background-color: #cecece;"  
  5.         align="center">  
  6.         <tbody>  
  7.             <tr>  
  8.                 <td align="center">  
  9.                     <asp:Label ID="lblError" runat="server"></asp:Label>  
  10.                 </td>  
  11.             </tr>  
  12.             <tr>  
  13.                 <td width="30%" align="right">  
  14.                     User ID :  
  15.                 </td>  
  16.                 <td width="70%">  
  17.                     <asp:TextBox ID="txtLogin" runat="server" Width="175px" MaxLength="20" AutoCompleteType="Disabled"></asp:TextBox>  
  18.                 </td>  
  19.             </tr>  
  20.             <tr>  
  21.                 <td align="right">  
  22.                     Password :  
  23.                 </td>  
  24.                 <td>  
  25.                     <asp:TextBox ID="txtPassword" runat="server" Width="175px" MaxLength="20" AutoCompleteType="Disabled"  
  26.                         TextMode="Password"></asp:TextBox>  
  27.                 </td>  
  28.             </tr>  
  29.             <tr>  
  30.                 <td>  
  31.                 </td>  
  32.                 <td colspan="2" align="left">  
  33.                     <div>  
  34.                         <asp:Image ImageUrl="ghCaptcha.ashx" runat="server" ID="imgCaptcha" />  
  35.                     </div>  
  36.                 </td>  
  37.             </tr>  
  38.             <tr>  
  39.                 <td align="right">  
  40.                     Enter Code :  
  41.                 </td>  
  42.                 <td>  
  43.                     <asp:TextBox ID="txtCode" runat="server" Width="175px" MaxLength="5" AutoCompleteType="Disabled"></asp:TextBox>  
  44.                 </td>  
  45.             </tr>  
  46.             <tr>  
  47.                 <td colspan="2" align="center">  
  48.                     <asp:Button ID="btnLogin" runat="server" Text="Login" />  
  49.                 </td>  
  50.             </tr>  
  51.         </tbody>  
  52.     </table>  
  53.     </form>  
The page has the following controls:

controls

Assign an ImageUrl property of an Image control as Path of the ghCaptcha.ashx file.

Step 6

The following is the code behind of login.aspx.cs:

  1. #region " [ using ] "  
  2. using System;  
  3. using System.Web.UI;  
  4. #endregion  
  5.   
  6. public partial class Login : System.Web.UI.Page  
  7. {  
  8.     protected void Page_Load(object sender, EventArgs e)  
  9.     {  
  10.         if (!Page.IsPostBack)  
  11.         {  
  12.             UpdateCaptchaText();  
  13.         }  
  14.     }  
  15.  
  16.     #region " [ Button Event ] "  
  17.     protected void btnRefresh_Click(object sender, ImageClickEventArgs e)  
  18.     {  
  19.         UpdateCaptchaText();  
  20.     }  
  21.   
  22.   
  23.     protected void btnLogin_Click(object sender, EventArgs e)  
  24.     {  
  25.   
  26.     }  
  27.     #endregion  
  28.     #region " [ Private Function ] "  
  29.     private void UpdateCaptchaText()  
  30.     {  
  31.         txtCode.Text = string.Empty;  
  32.         Random randNum = new Random();  
  33.   
  34.         //Store the captcha text in session to validate  
  35.         Session["Captcha"] = randNum.Next(10000, 99999).ToString();  
  36.         imgCaptcha.ImageUrl = "~/ghCaptcha.ashx?" + Session["Captcha"];  
  37.     }  
  38.     #endregion  
  39. }  

The value of Session["Captcha"] is updated in the Page_Load event of login.aspx.cs and is accessed in the handler page and session code used to generate the CAPTCHA image.

Step 7

Build and run it.

The Login Page Visuals os as below:

Page Visuals
Step 8

The following are enhancements (included in the source code download).

  1. A Refresh button beside the CAPTCHA image for changing the CAPTCHA without a page postback:

    Refresh button

  2. Page validation:

    Page validation

Up Next
    Ebook Download
    View all
    Learn
    View all