


C# verification code creation and usage sample code sharing
This article mainly introduces CVerification code 's creation and use methods, combined with examples, a more detailed analysis of the creation, verification and other operating steps and related techniques of C# verification code. Friends in need can refer to the following
The examples of this article describe the C# verification code The creation and use methods are shared with everyone for your reference. The details are as follows:
1. C# Create verification code
① Create the verification code page (ValidateCode.aspx)
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>获取验证码</title> </head> <body> <form id="form1" runat="server"> <p>获取验证码</p> </form> </body> </html>
② Write the code to obtain the verification code (ValidateCode.aspx.cs)
/// <summary> /// 验证码类型(0-字母数字混合,1-数字,2-字母) /// </summary> private string validateCodeType = "0"; /// <summary> /// 验证码字符个数 /// </summary> private int validateCodeCount = 4; /// <summary> /// 验证码的字符集,去掉了一些容易混淆的字符 /// </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) { //取消缓存 Response.BufferOutput = true; Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1)); Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AppendHeader("Pragma", "No-Cache"); //获取设置参数 if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"])) { validateCodeType = Request.QueryString["validateCodeType"]; } if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"])) { int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount); } //生成验证码 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)]; // 要求全为数字或字母 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 { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(System.Drawing.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 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); } //画图片的前景噪音点 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())); } //画图片的边框线 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
The code is as follows:
<img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick ="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
② Create the verification code test page (ValidateTest.aspx)
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>验证码测试</title> </head> <body> <form id="form1" runat="server"> <p> <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="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;"> <asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click" /> </p> </form> </body> </html>
③ Write the submission code for the verification code test (ValidateTest.aspx.cs)
protected void btnVal_Click(object sender, EventArgs e) { bool result = false; //验证结果 string userCode = this.txtValidate.Value; //获取用户输入的验证码 if (String.IsNullOrEmpty(userCode)) { //请输入验证码 return; } string validCode = this.Session["CheckCode"] as String; //获取系统生成的验证码 if (!string.IsNullOrEmpty(validCode)) { if (userCode.ToLower() == validCode.ToLower()) { //验证成功 result = true; } else { //验证失败 result = false; } } }
The above is the detailed content of C# verification code creation and usage sample code sharing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.
