ASP.NET Image Verification Code for logging (CSASPNETVerificationImage)

Introduction

This sample will demo you how to create an image verification code in ASP.NET. Whether registered or logged in, many times we all need the verification code in order to prevent malicious actions. Such as: auto registration by “Automatic-Teller Registration Machine” or the malicious password cracking. We provide a program to acquire a specified number of characters or symbols, and add some interference with the line, and then output a picture at the same time save the value in session. The user input content according to the display contents of the picture, and then to compare the input with the value in SESSION.  According to the results of the comparison, we will determine the follow-up operations.

Running the Sample

Please follow the steps below.

Step 1: Open the CSASPNETVerificationImage.sln file.

 

Step 2: Right-click the Default.aspx page then select "View in Browser".

Enter the characters in the picture and then we will see as below:

If we do not enter the characters in the picture. The page will be shown as below:

 

Step 3: Validation is completed.

Using the Code

Code Logical:                                                                                                                                                                                                                              

Step 1: Create a C# "ASP.NET Web Application" in Visual Studio /Visual Web Developer. Name it as "CSASPNETVerificationImage".

 

Step 2: Follow the steps below to add a generic handler to our solution.
Right-click the solution>> add a new item >> Generic Handler.

Step 3: Code will be rewritten as follows:

- C# code snippet -
 
public class ImageHandler : IHttpHandler, IRequiresSessionState
   {
 
       public void ProcessRequest(HttpContext context)
       {
           // Whether to generate verification code or not.
           bool isCreate = true;
 
           // Session["CreateTime"]: The createTime of verification code
           if (context.Session["CreateTime"] == null)
           {
               context.Session["CreateTime"] = DateTime.Now;
           }
           else
           {
               DateTime startTime = Convert.ToDateTime(context.Session["CreateTime"]);
               DateTime endTime = Convert.ToDateTime(DateTime.Now);
               TimeSpan ts = endTime - startTime;
 
               // The time interval to generate a verification code.
               if (ts.Minutes > 15)
               {
                   isCreate = true;
                   context.Session["CreateTime"] = DateTime.Now;
               }
               else
               {
                   isCreate = false;
               }
           }
 
 
           context.Response.ContentType = "image/gif";
           //Create Bitmap object and to draw
           Bitmap basemap = new Bitmap(200, 60);
           Graphics graph = Graphics.FromImage(basemap);
           graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
           Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
           Random r = new Random();
           string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz0123456789";
           string letter;
           StringBuilder s = new StringBuilder();
 
           if (isCreate)
           {
               // Add a random five-letter
               for (int x = 0; x < 5; x++)
               {
                   letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
                   s.Append(letter);
 
                   // Draw the String
                   graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
               }
           }
           else
           {
               // Using the previously generated verification code.
               string currentCode = context.Session["ValidateCode"].ToString();
               s.Append(currentCode);
 
               foreach (char item in currentCode)
               {
                   letter = item.ToString();
                   // Draw the String
                   graph.DrawString(letter, font, new SolidBrush(Color.Black), currentCode.IndexOf(item) * 38, r.Next(0, 15));
               }
           }
 
           // Confusion background
           Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
           for (int x = 0; x < 10; x++)
           {
               graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
           }
 
           // Save the picture to the output stream     
           basemap.Save(context.Response.OutputStream, ImageFormat.Gif);
           // If you do not realize the IRequiresSessionState,it will be wrong here,and it can not generate a picture also.
           context.Session["ValidateCode"] = s.ToString();
           context.Response.End();
 
       }
 
       public bool IsReusable
       {
           get
           {
               return false;
           }
       }
   }
 
- end -

[Note] The Handler class is not only need to implement the IHttpHandler interface (apparently), in order to use the SessionState Handler class we also need to implement the IRequiresSessionState interface. For this interface, the MSDN explanation of like this: Specifies that the target HTTP handlerrequires read and write access to session-state values. This is a marker interface and has no methods.

Step 4: Modify the code of the test page.

- HTML code snippet -
 
<asp:TextBox ID="tbCode" runat="server"></asp:TextBox>
      <asp:Image ImageUrl="~/ImageHandler.ashx" runat="server" />
      <asp:Button ID="btnOK" runat="server" Text="Validate" OnClick="btnOK_Click" />
      <asp:Literal ID="ltrMessage" runat="server"></asp:Literal>
 
- end -

The image will show the Image Verification Code. The button will be used to validate and the Literal will be used to show the result.

The code of the click event of button as shown below:

- C# code snippet -
 
/// <summary>
       /// Compare the value in session and type. If equal, set a success to the text of Literal, otherwise failed.
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
       protected void btnOK_Click(object sender, EventArgs e)
       {
           if (tbCode.Text.Trim().ToLower().Equals(Session["ValidateCode"].ToString().ToLower()))
           {
               ltrMessage.Text = "success";
           }
           else
           {
               ltrMessage.Text = "failed";
           }
       }
 
- end -

Step 5: You can debug and test it.

More Information
IRequiresSessionState Interface

 http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate.aspx
IHttpHandler Interface
http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx
IHttpHandler.ProcessRequest Method
http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.processrequest