Home Backend Development C#.Net Tutorial asp.net verification code generation, refresh and verification

asp.net verification code generation, refresh and verification

Jan 13, 2017 pm 01:57 PM

Verification code technology is set up to prevent brute force cracking, etc. Nowadays, general website registrations and other websites provide verification code functions, especially Tencent’s long list. The article refers to other people's code. Once you have it, there is no need to write anymore. You can read it. However, I found two PageLoad problems during testing. Just two comments. Namespaces were also modified. At the same time, complete verification instructions are provided:
1 Create a new VerifyCode.aspx
cs file code as follows:

using System; 
using System.Collections; 
using System.ComponentModel; 
using System.Data; 
using System.Web; 
using System.Web.SessionState; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.HtmlControls; 
using System.Drawing; 
using System.Drawing.Imaging; 
using System.Drawing.Text; 
/**///// <summary> 
/// 页面验证码程序 
/// 使用:在页面中加入HTML代码 <img src="VerifyCode.aspx"> 
/// </summary> 
public partial class VerifyCode : System.Web.UI.Page 
...{ 
static string[] FontItems = new string[] ...{ "Arial", 
"Helvetica", 
"Geneva", 
"sans-serif", 
"Verdana" 
}; 
static Brush[] BrushItems = new Brush[] ...{ Brushes.OliveDrab, 
Brushes.ForestGreen, 
Brushes.DarkCyan, 
Brushes.LightSlateGray, 
Brushes.RoyalBlue, 
Brushes.SlateBlue, 
Brushes.DarkViolet, 
Brushes.MediumVioletRed, 
Brushes.IndianRed, 
Brushes.Firebrick, 
Brushes.Chocolate, 
Brushes.Peru, 
Brushes.Goldenrod 
}; 
static string[] BrushName = new string[] ...{ "OliveDrab", 
"ForestGreen", 
"DarkCyan", 
"LightSlateGray", 
"RoyalBlue", 
"SlateBlue", 
"DarkViolet", 
"MediumVioletRed", 
"IndianRed", 
"Firebrick", 
"Chocolate", 
"Peru", 
"Goldenrod" 
}; 
private static Color BackColor = Color.White; 
private static Pen BorderColor = Pens.DarkGray; 
private static int Width = 52; 
private static int Height = 21; 
private Random _random; 
private string _code; 
private int _brushNameIndex; 
override protected void OnInit(EventArgs e) 
...{ 
// 
// CODEGEN: This call is required by the ASP.NET Web Form Designer. 
// 
//InitializeComponent(); 
//base.OnInit(e); 
} 
/**//**//**//// <summary> 
/// Required method for Designer support - do not modify 
/// the contents of this method with the code editor. 
/// </summary> 
private void InitializeComponent() 
...{ 
//this.Load += new System.EventHandler(this.Page_Load); 
} 
/**//// <summary> 
/// 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
public void Page_Load(object sender, System.EventArgs e) 
...{ 
if (!IsPostBack) 
...{ 
// 
// TODO : initialize 
// 
this._random = new Random(); 
this._code = GetRandomCode(); 
// 
// TODO : use Session["code"] save the VerifyCode 
// 
Session["code"] = this._code; 
// 
// TODO : output Image 
// 
this.SetPageNoCache(); 
this.OnPaint(); 
} 
} 
/**//**//**//// <summary> 
/// 设置页面不被缓存 
/// </summary> 
private void SetPageNoCache() 
...{ 
Response.Buffer = true; 
Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1); 
Response.Expires = 0; 
Response.CacheControl = "no-cache"; 
Response.AppendHeader("Pragma","No-Cache"); 
} 
/**//**//**//// <summary> 
/// 取得一个 4 位的随机码 
/// </summary> 
/// <returns></returns> 
private string GetRandomCode() 
...{ 
return Guid.NewGuid().ToString().Substring(0, 4); 
} 
/**//**//**//// <summary> 
/// 随机取一个字体 
/// </summary> 
/// <returns></returns> 
private Font GetFont() 
...{ 
int fontIndex = _random.Next(0, FontItems.Length); 
FontStyle fontStyle = GetFontStyle(_random.Next(0, 2)); 
return new Font(FontItems[fontIndex], 12, fontStyle); 
} 
/**//**//**//// <summary> 
/// 取一个字体的样式 
/// </summary> 
/// <param name="index"></param> 
/// <returns></returns> 
private FontStyle GetFontStyle(int index) 
...{ 
switch (index) 
...{ 
case 0: 
return FontStyle.Bold; 
case 1: 
return FontStyle.Italic; 
default: 
return FontStyle.Regular; 
} 
} 
/**//**//**//// <summary> 
/// 随机取一个笔刷 
/// </summary> 
/// <returns></returns> 
private Brush GetBrush() 
...{ 
int brushIndex = _random.Next(0, BrushItems.Length); 
_brushNameIndex = brushIndex; 
return BrushItems[brushIndex]; 
} 
/**//**//**//// <summary> 
/// 绘画事件 
/// </summary> 
private void OnPaint() 
...{ 
Bitmap objBitmap = null; 
Graphics g = null; 
try 
...{ 
objBitmap = new Bitmap(Width, Height); 
g = Graphics.FromImage(objBitmap); 
Paint_Background(g); 
Paint_Text(g); 
Paint_TextStain(objBitmap); 
Paint_Border(g); 
objBitmap.Save(Response.OutputStream, ImageFormat.Gif); 
Response.ContentType = "image/gif"; 
} 
catch ...{} 
finally 
...{ 
if (null != objBitmap) 
objBitmap.Dispose(); 
if (null != g) 
g.Dispose(); 
} 
} 
/**//**//**//// <summary> 
/// 绘画背景颜色 
/// </summary> 
/// <param name="g"></param> 
private void Paint_Background(Graphics g) 
...{ 
g.Clear(BackColor); 
} 
/**//**//**//// <summary> 
/// 绘画边框 
/// </summary> 
/// <param name="g"></param> 
private void Paint_Border(Graphics g) 
...{ 
g.DrawRectangle(BorderColor, 0, 0, Width - 1, Height - 1); 
} 
/**//**//**//// <summary> 
/// 绘画文字 
/// </summary> 
/// <param name="g"></param> 
private void Paint_Text(Graphics g) 
...{ 
g.DrawString(_code, GetFont(), GetBrush(), 3, 1); 
} 
/**//**//**//// <summary> 
/// 绘画文字噪音点 
/// </summary> 
/// <param name="g"></param> 
private void Paint_TextStain(Bitmap b) 
...{ 
for (int n=0; n<30; n++) 
...{ 
int x = _random.Next(Width); 
int y = _random.Next(Height); 
b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex])); 
} 
} 
}
Copy after login

2 Page reference:

Generally, the refresh function needs to be provided at the same time (change one if you can't see clearly), the code is as follows
Refresh verification code
If a master page is used, use the following code:
<%----%>
Refresh verification code
The javascript corresponding to the hyperlink is as follows:

3 Judgment Verification
The above code stores the verification code in the Session and is marked with code. Read the code Session["code"].ToString();
In use, we only need to compare whether Session["code"].ToString() and the string entered in the text box (TextBoxCode.Text) are the same. judge.
if(Session["code"].ToString().Trim().Equals(TextBoxCode.Text.Trim()))
...{
Response.Write("Success");
}
Test passed!

For more asp.net verification code generation and refresh and verification related articles, please pay attention to the PHP Chinese website!

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# as a Versatile .NET Language: Applications and Examples C# as a Versatile .NET Language: Applications and Examples Apr 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 and the Future: Adapting to New Technologies C# .NET and the Future: Adapting to New Technologies Apr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Apr 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.

C# and the .NET Runtime: How They Work Together C# and the .NET Runtime: How They Work Together Apr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# and .NET: Understanding the Relationship Between the Two C# and .NET: Understanding the Relationship Between the Two Apr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C# .NET Development: A Beginner's Guide to Getting Started C# .NET Development: A Beginner's Guide to Getting Started Apr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

See all articles