search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of how to generate ASP.NET verification code

General verification code generation methods are the same, the main steps are two steps

The first step: Randomly generate the numbers or letters of the system verification code, and by the way, add the randomly generated numbers or letters Write to Cookies or Session.

Step 2: Use the numbers or letters randomly generated in the first step to synthesize the picture.

It can be seen that the complexity of the verification code is mainly completed in the second step. You can set it according to the complexity you want.

Let’s take a look:

Step 1: How to randomly generate numbers or letters

/// <summary>
  /// 生成验证码的随机数
  /// </summary>
  /// <returns>返回五位随机数</returns>
  private string GenerateCheckCode()
  {
    int number;
    char code;
    string checkCode = String.Empty;
 
    Random random = new Random();
 
    for (int i = 0; i < 5; i++)//可以任意设定生成验证码的位数
    {
      number = random.Next();
 
      if (number % 2 == 0)
        code = (char)(&#39;0&#39; + (char)(number % 10));
      else
        code = (char)(&#39;A&#39; + (char)(number % 26));
 
      checkCode += code.ToString();
    }
 
    Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));//写入COOKIS
    Session["CheckCode"] = checkCode; //写入Session,可以任意选一下
    return checkCode;
  }

Step 2: Generate pictures

/// <summary>
  /// 生成验证码图片
  /// </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
    {
      //生成随机生成器
      Random random = new Random();
 
      //清空图片背景色
      g.Clear(Color.White);
 
      //画图片的背景噪音线
      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);
 
      //画图片的前景噪音点
      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()));
      }
 
      //画图片的边框线
      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
    {//释放对象资源
      g.Dispose();
      image.Dispose();
    }

* Complete program

First add a checkCode.aspx file to the project in VS2005, and add the following complete code to the checkCode.aspx.cs code file

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());//调用下面两个方法;
  }
 
  /// <summary>
  /// 生成验证码的随机数
  /// </summary>
  /// <returns>返回五位随机数</returns>
  private string GenerateCheckCode()
  {
    int number;
    char code;
    string checkCode = String.Empty;
 
    Random random = new Random();
 
    for (int i = 0; i < 5; i++)//可以任意设定生成验证码的位数
    {
      number = random.Next();
 
      if (number % 2 == 0)
        code = (char)(&#39;0&#39; + (char)(number % 10));
      else
        code = (char)(&#39;A&#39; + (char)(number % 26));
 
      checkCode += code.ToString();
    }
 
    Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));//写入COOKIS
    Session["CheckCode"] = checkCode; //写入Session,可以任意选一下
    return checkCode;
  }
 
 
  /// <summary>
  /// 生成验证码图片
  /// </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
    {
      //生成随机生成器
      Random random = new Random();
 
      //清空图片背景色
      g.Clear(Color.White);
 
      //画图片的背景噪音线
      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);
 
      //画图片的前景噪音点
      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()));
      }
 
      //画图片的边框线
      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
    {//释放对象资源
      g.Dispose();
      image.Dispose();
    }
  }
 
}

Do all the above pages that generate verification codes Okay, let's call it and see:

Add the Image control where you need to use the verification code


The verification code will be displayed on the Image control!

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

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

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

Get the value of Session Value Session["CheckCode"].ToString() (It is best to first determine whether the Session is empty)

If you do not want to be case sensitive, convert the values ​​entered by the user and the values ​​of Cookies or Session into uppercase or All lowercase

With 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())
        //这样写可以不能区分大小写
      {
        Response.Write("Session is right");
 
      }
      else
      {
        Response.Write("Session is wrong");
      }
    }
  }

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

For more detailed articles on how to generate ASP.NET verification codes, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.