An example of how to generate graphic verification code by using ashx in


In this paper, the method of using ashx to generate graphic verification code in is introduced. The details are as follows:

I don’t need to say more about the benefits of captcha. You all know it. I saw that someone wrote the captcha directly in the ASPX page on the Internet, that is to say, requesting the captcha in this way is equivalent to requesting a page, which is very unscientific. As shown below

<form runat="server">
    <asp:Image ID="Image1" runat="server" ImageUrl="Default.aspx" />
    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

Looking at the code, I feel that the people who write the code are not good enough to beat. It’s really depressing to write the code like this. Do not write script to switch.

Now I’ll introduce a way to realize this function

1. Write an ashx to generate a graphic verification code

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.SessionState;
using System.Drawing;
namespace usechecknum.ashx
  /// <summary>
  ///Summary description of $codebehindclassname $
  /// </summary>
  [WebService(Namespace = "")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  public class doCreateNum : IHttpHandler,IRequiresSessionState
    public void ProcessRequest(HttpContext context)
      context.Response.ContentType = "text/html";
      string checkCode = GetValidation(5); //  Generate 5 random captcha characters
      context.Session["Code"] = checkCode; // Save the string to the session for verification when needed
      System.Drawing.Bitmap image = new System.Drawing.Bitmap(70, 22);
      Graphics g = Graphics.FromImage(image);
        //Generating random generators
        Random random = new Random();
        //Clear image background color
        //Draw the background noise line of the picture
        int i;
        for (i = 0; i < 25; i++)
          int x1 = random.Next(image.Width);
          int x2 = random.Next(image.Width);
          int y1 = random.Next(image.Height);
          int y2 = random.Next(image.Height);
          g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
        Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);
        g.DrawString(checkCode, font, brush, 2, 2);
        //Draw the foreground noise points of the picture
        g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        context.Response.ContentType = "image/Gif";
    public string GetValidation(int num)
      string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //" Or write Chinese characters“
      string validatecode = "";
      Random rd = new Random();
      for (int i = 0; i < num; i++)
        validatecode += str.Substring(rd.Next(0, str.Length), 1);
      return validatecode;
    public bool IsReusable
        return false;

2. The captcha is displayed on the page. Because what we generate is a graph, we can write it directly in the < img / > tag. We only need to write a simple script to switch the captcha by clicking the mouse

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="usechecknum._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" >
<head runat="server">
  The use of < title > captcha
<script language="javascript" type="text/javascript">
  function changeCode() {
    var imgNode = document.getElementById("vimg");
    imgNode.src = "ashx/doCreateNum.ashx?t=" + (new Date()).valueOf(); //  Add a time parameter here to prevent the problem of browser caching
  <form runat="server">
   Please input the verification code: < input type = "text" name = "checknum" / > < img SRC = "ashx / docreatenum. Ashx" onclick = "changecode()" / >

After a long time, it’s time to see what the generated captcha looks like

For more information about, readers who are interested in it can see the special topic of this website:《Summary of string operation skills》、《 operation XML skill summary》、《Summary of the skills of operating JSON with》、《Summary of file operation skills》、《Summary of Ajax skills》And《Summary of cache operation skills》。

I hope that this paper will be helpful to programming.