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");
}
測試通過!

熱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#.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#在企業級應用、遊戲開發、移動應用和Web開發中均有廣泛應用。 1)在企業級應用中,C#常用於ASP.NETCore開發WebAPI。 2)在遊戲開發中,C#與Unity引擎結合,實現角色控制等功能。 3)C#支持多態性和異步編程,提高代碼靈活性和應用性能。

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。
