Detailed explanation of the generation method of ASP. NET verification code

  • 2021-07-22 09:32:15
  • OfStack

1 The generation method of verification code is the same, and the main steps are two steps

Step 1: Randomly give the number or letter of 1 system verification code, and write the randomly generated number or letter into Cookies or Session by the way.

Step 2: Compose the picture with the numbers or letters randomly selected from Step 1.

It can be seen that the complexity of verification code is mainly completed in the second step, and you can set it according to your own complexity.

Let's take a look at:

Step 1: Method of randomly generating numbers or letters


/// <summary>
  ///  Generate random number of verification code 
  /// </summary>
  /// <returns> Return 5 Bit random number </returns>
  private string GenerateCheckCode()
  {
    int number;
    char code;
    string checkCode = String.Empty;

    Random random = new Random();

    for (int i = 0; i < 5; i++)// You can arbitrarily set the number of digits to generate the verification code 
    {
      number = random.Next();

      if (number % 2 == 0)
        code = (char)('0' + (char)(number % 10));
      else
        code = (char)('A' + (char)(number % 26));

      checkCode += code.ToString();
    }

    Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));// Write COOKIS
    Session["CheckCode"] = checkCode; // Write Session , you can choose at will 1 Under 
    return checkCode;
  }

Step 2: Generate a picture


/// <summary>
  ///  Generate verification code picture 
  /// </summary>
  /// <param name="checkCode"></param>
  private void CreateCheckCodeImage(string checkCode)
  {
    if (checkCode == null || checkCode.Trim() == String.Empty)
      return;

    Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
    Graphics g = Graphics.FromImage(image);

    try
    {
      // Generate random generator 
      Random random = new Random();

      // Clear the background color of the picture 
      g.Clear(Color.White);

      // Draw the background noise line of the picture 
      for (int 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.FontStyle.Italic));
      LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
      g.DrawString(checkCode, font, brush, 2, 2);

      // Noise points in the foreground of drawing pictures 
      for (int i = 0; i < 100; i++)
      {
        int x = random.Next(image.Width);
        int y = random.Next(image.Height);

        image.SetPixel(x, y, Color.FromArgb(random.Next()));
      }

      // Draw the border line of the picture 
      g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

      MemoryStream ms = new MemoryStream();
      image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
      Response.ClearContent();
      Response.ContentType = "image/Gif";
      Response.BinaryWrite(ms.ToArray());
    }
    finally
    {// Release object resources 
      g.Dispose();
      image.Dispose();
    }

:: Complete procedures

First, add 1 checkCode. aspx file in the project of VS 2005, and add the following complete code in the code file of checkCode. aspx. cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;

public partial class checkCode : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    CreateCheckCodeImage(GenerateCheckCode());// Call the following two methods ;
  }

  /// <summary>
  ///  Generate random number of verification code 
  /// </summary>
  /// <returns> Return 5 Bit random number </returns>
  private string GenerateCheckCode()
  {
    int number;
    char code;
    string checkCode = String.Empty;

    Random random = new Random();

    for (int i = 0; i < 5; i++)// You can arbitrarily set the number of digits to generate the verification code 
    {
      number = random.Next();

      if (number % 2 == 0)
        code = (char)('0' + (char)(number % 10));
      else
        code = (char)('A' + (char)(number % 26));

      checkCode += code.ToString();
    }

    Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));// Write COOKIS
    Session["CheckCode"] = checkCode; // Write Session , you can choose at will 1 Under 
    return checkCode;
  }


  /// <summary>
  ///  Generate verification code picture 
  /// </summary>
  /// <param name="checkCode"></param>
  private void CreateCheckCodeImage(string checkCode)
  {
    if (checkCode == null || checkCode.Trim() == String.Empty)
      return;

    Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
    Graphics g = Graphics.FromImage(image);

    try
    {
      // Generate random generator 
      Random random = new Random();

      // Clear the background color of the picture 
      g.Clear(Color.White);

      // Draw the background noise line of the picture 
      for (int 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.FontStyle.Italic));
      LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
      g.DrawString(checkCode, font, brush, 2, 2);

      // Noise points in the foreground of drawing pictures 
      for (int i = 0; i < 100; i++)
      {
        int x = random.Next(image.Width);
        int y = random.Next(image.Height);

        image.SetPixel(x, y, Color.FromArgb(random.Next()));
      }

      // Draw the border line of the picture 
      g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

      MemoryStream ms = new MemoryStream();
      image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
      Response.ClearContent();
      Response.ContentType = "image/Gif";
      Response.BinaryWrite(ms.ToArray());
    }
    finally
    {// Release object resources 
      g.Dispose();
      image.Dispose();
    }
  }

}

The above pages for generating verification codes are all ready. Let's call and have a look:

Add Image control where you need to use verification code

< asp:Image ID="Image1" runat="server" ImageUrl="~/checkCode.aspx" / >

In this way, the verification code will be displayed on the Image control!

The display is ready, of course, we have to judge whether the user's input is correct!

As long as we get the value entered by the user and compare it with Cookis or Session, it will be OK

Take the value of Cookies Request. Cookies ["CheckCode"]. Value

Take the value of Session, Session ["CheckCode"]. ToString () (it is best to determine whether Session is empty first)

If it is not case sensitive, convert the value entered by the user and the value of Cookies or Session to uppercase or both lowercase

Attached usage


protected void Button1_Click(object sender, EventArgs e)
  {
    if (Request.Cookies["CheckCode"].Value == TextBox1.Text.Trim().ToString())
    {
      Response.Write("Cookies is right");
    }
    else
    {
      Response.Write("Cookies is wrong");
    }

    if (Session["CheckCode"] != null)
    {
      if (Session["CheckCode"].ToString().ToUpper() == TextBox1.Text.Trim().ToString().ToUpper())
        // This writing can not be case sensitive 
      {
        Response.Write("Session is right");

      }
      else
      {
        Response.Write("Session is wrong");
      }
    }
  }

The above is the whole content of this article, teaching you how to make ASP. NET verification code, I hope you like it.


Related articles: