search
HomeBackend DevelopmentC#.Net TutorialHow to generate and use .net verification code

Small Classroom: The role of verification code:

A few years ago, most websites, forums and the like did not have verification codes, because for ordinary users, verification codes only increased user operations. Reduced user experience. However, various spamming robots, voting robots, and malicious registration robots emerged in an endless stream, which greatly increased the burden on the website and also brought a large amount of junk data to the website database. In order to prevent the destruction of various robot programs, programmers came up with verification codes that can only be recognized by the human eye and are not easily recognized by programs!

The verification code is a picture, with letters, numbers and even Chinese characters as the content of the picture. In this way, the content in the picture is easy to identify with the human eye, but the program will not be able to identify it. Before performing database operations (such as login verification, voting, posting, replying, registration, etc.), the program first verifies whether the verification code submitted by the client is the same as the content in the picture. If it is the same, it will perform the database operation. If it is different, it will prompt a verification code error. , no database operations are performed. In this way, all kinds of robot programs will be blocked!

But with the development of computer science, technologies such as pattern recognition are becoming more and more mature, so the guy who writes the robot program can recognize the content written directly in the picture through the program, and then submit it to the server for verification. The code will be useless. In order to prevent the recognition of robot programs, the image generation of verification codes is also constantly evolving, adding interference points, interference lines, text deformation, changing angle positions, different colors... Various technologies to prevent computer recognition are also applied to verification codes. In the competition between these two technologies, the verification code we see now is formed. Many people are already complaining, "What kind of verification code is this? The human eye can't tell what it is." Everything is helpless.

Understanding the function of the verification code, let’s write a simple example of generating and using the verification code

How to generate and use .net verification code

First create a page to display the verification code and Determine whether the verification code input is correct

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 <script type="text/javascript">
 //点击切换验证码
 function f_refreshtype() {
 var Image1 = document.getElementById("img");
 if (Image1 != null) {
 Image1.src = Image1.src + "?";
 }
 } 
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <table>
 <tr>
 <td>
  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
 </td>
 <td>
  <img  src="/static/imghwm/default1.png"  data-src="png.aspx"  class="lazy"   id="img" onclick="f_refreshtype()" / alt="How to generate and use .net verification code" >
 </td>
 <td>
  <asp:Button ID="Button1" runat="server" Text="确定" />
 </td>
 </tr>
 </table>
 </div>
 </form>
</body>
</html>

The verification code is verified in the background of this page

protected void Page_Load(object sender, EventArgs e)
{
//生成的验证码被保存到session中
if (Session["CheckCode"] != null)
{
string checkcode = Session["CheckCode"].ToString();
if (this.TextBox1.Text == checkcode)
{
 ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert(&#39;验证码输入正确!&#39;)", true);
}
else
{
 ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert(&#39;验证码输入错误!&#39;)", true);
}
}
 
}

Generate verification code page png.aspx

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateCheckCodeImage(GenerateCheckCodes(4));
}
}
public void ShowAuthCode(Stream stream, out string code)
{
Random random = new Random();
code = random.Next(1000, 9999).ToString();
 
Bitmap bitmap = CreateAuthCode(code);
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
}
 
private string GenerateCheckCodes(int iCount)
{
int number;
string checkCode = String.Empty;
int iSeed = DateTime.Now.Millisecond;
System.Random random = new Random(iSeed);
for (int i = 0; i < iCount; i++)
{
number = random.Next(10);
checkCode += number.ToString();
}
Session["CheckCode"] = checkCode;
return checkCode;
}
 
private Bitmap CreateAuthCode(string str)
{
Font fn = new Font("宋体", 12);
Brush forecolor = Brushes.Black;
Brush bgcolor = Brushes.White;
PointF pf = new PointF(5, 5);
Bitmap bitmap = new Bitmap(100, 25);
Rectangle rec = new Rectangle(0, 0, 100, 25);
Graphics gh = Graphics.FromImage(bitmap);
gh.FillRectangle(bgcolor, rec);
gh.DrawString(str, fn, forecolor, pf);
return bitmap;
}
 
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
int iWordWidth = 15;
int iImageWidth = checkCode.Length * iWordWidth;
Bitmap image = new Bitmap(iImageWidth, 20);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器 
Random random = new Random();
//清空图片背景色 
g.Clear(Color.White);
 
//画图片的背景噪音点
for (int i = 0; i < 20; 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);
}
 
//画图片的背景噪音线 
for (int i = 0; i < 2; i++)
{
 int x1 = 0;
 int x2 = image.Width;
 int y1 = random.Next(image.Height);
 int y2 = random.Next(image.Height);
 if (i == 0)
 {
 g.DrawLine(new Pen(Color.Gray, 2), x1, y1, x2, y2);
 }
 
}
 
 
for (int i = 0; i < checkCode.Length; i++)
{
 
 string Code = checkCode[i].ToString();
 int xLeft = iWordWidth * (i);
 random = new Random(xLeft);
 int iSeed = DateTime.Now.Millisecond;
 int iValue = random.Next(iSeed) % 4;
 if (iValue == 0)
 {
 Font font = new Font("Arial", 13, (FontStyle.Bold | System.Drawing.FontStyle.Italic));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Red, 1.5f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 1)
 {
 Font font = new System.Drawing.Font("楷体", 13, (FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.DarkRed, 1.3f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 2)
 {
 Font font = new System.Drawing.Font("宋体", 13, (System.Drawing.FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Green, Color.Blue, 1.2f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 3)
 {
 Font font = new System.Drawing.Font("黑体", 13, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Green, 1.8f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
}
//////画图片的前景噪音点 
//for (int i = 0; i < 8; 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);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}

More.net verification code generation and Please pay attention to the PHP Chinese website for articles related to usage methods!

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
Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor