最近在做一個系統,找到大三時候在學校做的項目,發現其中有點東西能夠拿來用用,例如登入介面驗證碼的實現。設計驗證碼的目的顯然是為了防止惡意大量登入,在asp中可以如下實現:
1、建立一個登入頁面,裡面加入一個驗證碼輸入框,後面接上一幅圖,圖片的來源地址為一個產生驗證碼的aspx頁面
驗證碼: <asp:TextBox ID="txtcheckcode" runat="server" Font-Names="微軟雅黑" Font-Size="Medium" Width="113px"> </asp:TextBox> <asp:Image ID="Image4" runat="server" ImageUrl="~/CheckCode.aspx" />
2、建立CheckCode.aspx頁面,只需要在head標記位之間加上點代碼
<%Response.Buffer = true; %> <%Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1); %> <%Response.Expires = 0; %> <%Response.CacheControl = "no-cache"; %>
3、在CheckCode.aspx.cs頁面中添加代碼
首先是添加使用者空間:
using System.Data.SqlClient;using System.Drawing;
再添加剩下的代碼:
protected void Page_Load(object sender, EventArgs e) { CreateCheckCodeImage(GenerateCheckCode()); } //建立驗證碼 private string GenerateCheckCode() { int number; char code; string CheckCode = string.Empty; System.Random random = new Random(); for (int i = 0; i < 6; i++) { number = random.Next(); if (number % 2 == 0) { code = (char)('0' + (char)(number % 10)); } else { code = (char)('a' + (char)(number % 26)); } CheckCode += code.ToString(); } Session["CheckCode"] = CheckCode; return CheckCode; } //產生驗證碼背景映像 private void CreateCheckCodeImage(string checkCode) { if (checkCode == null || checkCode.Trim() == string.Empty) return; System.Drawing.Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 13.5)), 22); Graphics g = Graphics.FromImage(image); try { //產生隨機產生器 Random random = new Random(); //清空圖片背景色 g.Clear(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 Pen(Color.Silver), x1, x2, y1, y2); } Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(checkCode, font, brush, 2, 2); //畫圖片的前景噪音點 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //畫圖片的邊框線 g.DrawRectangle(new Pen(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(); } }
當初這個登入模組是一個女生做的,雖然當時我做了系統的核心模組,而她只是做一個登入模組而已,但人家最後得的分數就是比我高,人家95分,我才90分,太囧了。