asp.net 验证码生成和刷新及验证
验证码技术是为了防止暴力破解等而设定的。现在一般的网站注册等都提供验证码功能,特别是腾讯更是长长的一串。文中参考了别人的代码。有了就没有必要再写了。可以读一下。不过我测试时发现了两次PageLoad的问题。注释了两句即可。同时修改了namespaces。同时提供完整的验证说明:
1 新建VerifyCode.aspx
cs文件代码如下:
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])); } } }
2 页面引用:
一般需要同时提供刷新功能(看不清楚换一张),代码如下
如使用了母版页,则用如下代码: <%--
刷新验证码
超链接对应的javascript如下:
3 判断验证
上述代码是将验证码存贮在Session中,用code来标志。读取代码Session["code"].ToString();
使用中,我们只需要比较Session["code"].ToString()和文本框输入的串(TextBoxCode.Text)是否相同即可进行判断。
if(Session["code"].ToString().Trim().Equals(TextBoxCode.Text.Trim()))
...{
Response.Write("Success");
}
测试通过!
更多asp.net 验证码生成和刷新及验证相关文章请关注PHP中文网!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

C#是一种现代、面向对象的编程语言,由微软开发并作为.NET框架的一部分。1.C#支持面向对象编程(OOP),包括封装、继承和多态。2.C#中的异步编程通过async和await关键字实现,提高应用的响应性。3.使用LINQ可以简洁地处理数据集合。4.常见错误包括空引用异常和索引超出范围异常,调试技巧包括使用调试器和异常处理。5.性能优化包括使用StringBuilder和避免不必要的装箱和拆箱。

C#.NET应用的测试策略包括单元测试、集成测试和端到端测试。1.单元测试确保代码的最小单元独立工作,使用MSTest、NUnit或xUnit框架。2.集成测试验证多个单元组合的功能,常用模拟数据和外部服务。3.端到端测试模拟用户完整操作流程,通常使用Selenium进行自动化测试。

C#.NET依然重要,因为它提供了强大的工具和库,支持多种应用开发。1)C#结合.NET框架,使开发高效便捷。2)C#的类型安全和垃圾回收机制增强了其优势。3).NET提供跨平台运行环境和丰富的API,提升了开发灵活性。

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

C#在企业级应用、游戏开发、移动应用和Web开发中均有广泛应用。1)在企业级应用中,C#常用于ASP.NETCore开发WebAPI。2)在游戏开发中,C#与Unity引擎结合,实现角色控制等功能。3)C#支持多态性和异步编程,提高代码灵活性和应用性能。

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

C#在.NET中的编程过程包括以下步骤:1)编写C#代码,2)编译为中间语言(IL),3)由.NET运行时(CLR)执行。C#在.NET中的优势在于其现代化语法、强大的类型系统和与.NET框架的紧密集成,适用于从桌面应用到Web服务的各种开发场景。

C#和.NET通过不断的更新和优化,适应了新兴技术的需求。1)C#9.0和.NET5引入了记录类型和性能优化。2).NETCore增强了云原生和容器化支持。3)ASP.NETCore与现代Web技术集成。4)ML.NET支持机器学习和人工智能。5)异步编程和最佳实践提升了性能。
