在網上有看到很多關於驗證碼的代碼,很多都只是生成一張驗證碼圖片,然而在實際登陸驗證模塊,驗證碼要怎么添加進去或者說怎么運用、和實際項目開發中要怎么使用驗證碼,我自己總結了幾點。
一、在實際開發登陸模塊的驗證碼,程序員是將驗證碼的文本值(字符串)存在Session中的,然后在登陸驗證的時候,通過Session取值進行判斷的,這樣效率會高很多。
二、然而在寫驗證碼的時候要想通過Session存值,就必須實現System.Web.SessionState.IRequiresSessionState這個接口
三、以一般處理程序(ashx頁面)為列,下面對驗證碼寫法和運用進行詳解
代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.Drawing; 4 using System.Linq; 5 using System.Web; 6 7 namespace vcodeDemo 8 { 9 /// <summary> 10 /// vcode 寫法的說明 11 /// </summary> 12 public class c01vcode : IHttpHandler,System.Web.SessionState.IRequiresSessionState 13 //如果要在一般處理程序中能夠正常使用session則必須實現IRequiresSessionState接口 14 { 15 public void ProcessRequest(HttpContext context) 16 { 17 //1 設置ContentType為圖片類型 18 context.Response.ContentType = "image/jpeg"; 19 20 //2 准備要作畫的圖片對象,寬度為80 高度為25 ,Bitmap:位圖 21 using (Image img = new Bitmap(80, 25)) 22 { 23 // 從img對象上定義畫家 24 using (Graphics g = Graphics.FromImage(img)) 25 { 26 //以白色來清除位圖的背景 27 g.Clear(Color.White); 28 29 //畫圖片的邊框為紅色,從左上角開始畫滿整個圖片 30 g.DrawRectangle(Pens.Red, 0, 0, img.Width - 1, img.Height - 1); 31 32 //在驗證碼文字前面畫50個噪點 33 this.DrawPoint(50, g, img.Width, img.Height); 34 35 //得到驗證碼文本字符串(隨機產生4個字符) 36 string vcode = this.GetVCode(4); 37 38 //保存驗證碼文本字符串到session中 39 context.Session["vcode"] = vcode; 40 41 //將驗證碼字符串寫入到圖片對象上 42 g.DrawString(vcode 43 , new Font("Arial", 16, FontStyle.Strikeout | FontStyle.Bold) // 給文本加中橫線和加粗 44 , new SolidBrush(Color.Red) 45 , new PointF(r.Next(15), r.Next(8)) 46 ); 47 48 //在驗證碼文字后面畫50個噪點 49 this.DrawPoint(50, g, img.Width, img.Height); 50 } 51 //將驗證碼輸出給瀏覽器 52 img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); 53 } 54 } 55 56 /// <summary> 57 /// 在圖片對象上畫噪點 58 /// </summary> 59 /// <param name="count"></param> 60 void DrawPoint(int count, Graphics g, int width, int height) 61 { 62 for (int i = 0; i < count; i++) 63 { 64 int x = r.Next(width); 65 int y = r.Next(height); 66 67 g.DrawLine(Pens.Blue 68 , new Point(x, y) 69 , new Point(x + 2, y + 2) 70 ); 71 } 72 } 73 74 /// <summary> 75 /// 定義產生隨機數的對象 76 /// </summary> 77 Random r = new Random(); 78 79 /// <summary> 80 /// 產生驗證碼文本字符串 81 /// </summary> 82 /// <param name="count"></param> 83 /// <returns></returns> 84 string GetVCode(int count) 85 { 86 //聲明返回值 87 string rescode = ""; 88 string codestr = "ABCDabcd123456789"; 89 char[] codeArr = codestr.ToArray(); 90 for (int i = 0; i < count; i++) 91 { 92 rescode += codeArr[r.Next(codestr.Length)]; 93 } 94 //返回字符串 95 return rescode; 96 } 97 98 public bool IsReusable 99 { 100 get 101 { 102 return false; 103 } 104 } 105 } 106 }
四、在驗證登陸判斷的時候,因為我們通過上下文對象的Session給驗證碼文本賦值並存入Session中去: context.Session["vcode"] = vcode;所有在進行驗證的時候可以使用Session["vcode"]進行取值,然后進行判斷。