Example of Creating and Using C Verification Code

  • 2021-11-30 01:16:32
  • OfStack

This paper describes the creation and use of C # verification code with examples. Share it for your reference, as follows:

1. C # Create Verification Code

① Create the Get Verification Code page (ValidateCode. aspx)


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title> Get verification code </title>
</head>
<body>
  <form id="form1" runat="server">
    <div> Get verification code </div>
  </form>
</body>
</html>

② Write the code for obtaining verification code (ValidateCode. aspx. cs)


/// <summary>
///  Verification code type (0- Alphanumeric mixture ,1- Figures ,2- Alphabet )
/// </summary>
private string validateCodeType = "0";
/// <summary>
///  Number of verification code characters 
/// </summary>
private int validateCodeCount = 4;
/// <summary>
///  The character set of the verification code has been removed 1 Some confusing characters 
/// </summary>
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
protected void Page_Load(object sender, EventArgs e)
{
  // Cache cancellation 
  Response.BufferOutput = true;
  Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
  Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
  Response.AppendHeader("Pragma", "No-Cache");
  // Get settings parameters 
  if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
  {
    validateCodeType = Request.QueryString["validateCodeType"];
  }
  if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
  {
    int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
  }
  // Generate verification code 
  this.CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
  char code ;
  string checkCode = String.Empty;
  System.Random random = new Random();
  for (int i = 0; i < validateCodeCount; i++)
  {
    code = character[random.Next(character.Length)];
    //  All numbers or letters are required 
    if (validateCodeType == "1")
    {
      if ((int)code < 48 || (int)code > 57)
      {
        i--;
        continue;
      }
    }
    else if (validateCodeType == "2")
    {
      if ((int)code < 65 || (int)code > 90)
      {
        i--;
        continue;
      }
    }
    checkCode += code;
  }
  Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
  this.Session["CheckCode"] = checkCode;
  return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{
  if (checkCode == null || checkCode.Trim() == String.Empty)
    return;
  System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*15.0+40)), 23);
  System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  try
  {
    // Generate random generator 
    Random random = new Random();
    // Clear the background color of the picture 
    g.Clear(System.Drawing.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 System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
    }
    System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
    int cySpace = 16;
    for (int i = 0; i < validateCodeCount; i++)
    {
      g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
    }
    // 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, System.Drawing.Color.FromArgb(random.Next()));
    }
    // Draw the border line of the picture 
    g.DrawRectangle(new System.Drawing.Pen(System.Drawing.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);
    Response.ClearContent();
    Response.ContentType = "image/Gif";
    Response.BinaryWrite(ms.ToArray());
  }
  finally
  {
    g.Dispose();
    image.Dispose();
  }
}

2. Use of verification code

① The front section of the verification code displays the code

<img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt=" Click Refresh Verification Code " title=" Click Refresh Verification Code " style="cursor: pointer;">

② Create verification code test page (ValidateTest. aspx)


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title> Verification code test </title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input runat="server" id="txtValidate" />
    <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt=" Click Refresh Verification Code " title=" Click Refresh Verification Code " style="cursor: pointer;">
    <asp:Button runat="server" id="btnVal" Text=" Submit " onclick="btnVal_Click" />
  </div>
  </form>
</body>
</html>

③ Write the submission code of verification code test (ValidateTest. aspx. cs)


protected void btnVal_Click(object sender, EventArgs e)
{
  bool result = false;  // Verification result 
  string userCode = this.txtValidate.Value; // Get the verification code entered by the user 
  if (String.IsNullOrEmpty(userCode))
  {
    // Please enter the verification code 
    return;
  }
  string validCode = this.Session["CheckCode"] as String; // Get the system-generated verification code 
  if (!string.IsNullOrEmpty(validCode))
  {
    if (userCode.ToLower() == validCode.ToLower())
    {
      // Verification succeeded 
      result = true;
    }
    else
    {
      // Validation failed 
      result = false;
    }
  }
}

For more readers interested in C # related content, please check the topics on this site: "Summary of C # Picture Operation Skills", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "C # Programming Thread Use Skills Summary"

I hope this article is helpful to everyone's C # programming.


Related articles: