ASP.NET驗證碼實現(附源碼)_實用技巧

來源:互聯網
上載者:User

首先看下效果實現(由於gif螢幕錄製軟體是即時找的,有些失禎)

代碼主要就是繪製驗證碼類的實現

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Drawing;using System.IO;namespace SecurityCodePic{ public class DrawingSecurityCode {  /// <summary>  /// 產生驗證碼,並返回  /// </summary>  /// <returns></returns>  public string GetSecurityCode(int n)  {   string code = GenerateCheckCode(n);   CreateCheckCodeImage(code);   return code;  }  /// <summary>  /// 動態產生指定數目的隨機數或字母  /// </summary>  /// <param name="num">整數</param>  /// <returns>返回驗證碼字串</returns>  private string GenerateCheckCode(int num)  {   int number;//定義變數   char code;   string checkCode = String.Empty; //Null 字元串,唯讀   Random random = new Random(); //定義隨機變數執行個體   for (int i=0; i < num;i++ )   {    //利用for迴圈產生指定數目的隨機數或字母    number = random.Next(); //返回一個小於指定的最大值的非負的隨機數 next有三個建構函式     if (number % 2 == 0)    {//產生一個一位元     code = (char)('0' + (char)(number % 10));    }    else    { //產生一個大寫字母     code = (char)('A'+(char)(number % 26));    }    checkCode += code.ToString();   }   return checkCode;  }  /// <summary>  /// 根據驗證碼字串產生驗證碼圖片  /// </summary>  /// <param name="checkCode">驗證碼字串</param>  private void CreateCheckCodeImage(string checkCode)  {   if (checkCode == null || checkCode.Trim() == String.Empty) return;   // 引用System.Drawing類庫   Bitmap myImage = new Bitmap(80, 30);//產生一個指定大小的位元影像   Graphics graphics = Graphics.FromImage(myImage); //從一個位元影像產生一個畫布   try   {    graphics.Clear(Color.White); //清除整個繪畫面並以指定的背景色填充,這裡是把背景色設為白色    Random random = new Random(); //執行個體化一個偽隨機數產生器    //畫圖片的前景噪音點,這裡有100個    for (int i = 0; i < 100; i++)    {     int x = random.Next(myImage.Width);     int y = random.Next(myImage.Height);     myImage.SetPixel(x, y, Color.FromArgb(random.Next()));//指定座標為x,y處的像素的顏色    }    //畫圖片的背景雜音線,這裡為2條    for (int i = 0; i < 2; i++)    {     int x1 = random.Next(myImage.Width);     int x2 = random.Next(myImage.Width);     int y1 = random.Next(myImage.Height);     int y2 = random.Next(myImage.Height);     graphics.DrawLine(new Pen(Color.Black), x1, y1, x2, y2); //繪製一條座標x1,y1到座標x2,y2的指定顏色的線條,這裡的線條為黑色    }    Font font = new Font("Arial", 15, FontStyle.Bold); //定義特定的文字格式設定,這裡的字型為Arial,大小為15,字型加粗    //根據矩形、起始顏色和結束顏色以及方向角度產生一個LinearGradientBrush執行個體---線性漸層    System.Drawing.Drawing2D.LinearGradientBrush brush =     new System.Drawing.Drawing2D.LinearGradientBrush(      new Rectangle(0, 0, myImage.Width, myImage.Height),//在座標0,0處執行個體化一個和myImage同樣大小的矩形      Color.Blue, Color.Red, 1.2f, true);    //繪製文本字串    graphics.DrawString(checkCode, font, brush, 2, 2);    //繪製有座標組、寬度和高度指定的矩形---畫圖片的邊框線    graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, myImage.Width - 1, myImage.Height - 1);    //建立其支援儲存空間為記憶體的流    MemoryStream ms = new MemoryStream();    //將此映像以指定格式儲存到指定的流中    myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //這裡是以gif的格式儲存到記憶體中    HttpContext.Current.Response.ClearContent(); //清除緩衝區流中的所有內容輸出    HttpContext.Current.Response.ContentType = "image/Gif"; //擷取或設定輸出資料流的HTTP MIME類型    HttpContext.Current.Response.BinaryWrite(ms.ToArray()); //將一個二進位字串寫入HTTP輸出資料流   }   finally   {    //釋放佔用資源    graphics.Dispose();    myImage.Dispose();   }  } }}


然後使用SecurityCode.ashx檔案調用上面類的方法實現

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace SecurityCodePic{ /// <summary> /// SecurityCode1 的摘要說明 /// </summary> public class SecurityCode1 : IHttpHandler {  public void ProcessRequest(HttpContext context)  {   DrawingSecurityCode sc = new DrawingSecurityCode();   string SecurityCode = sc.GetSecurityCode(6);  }  public bool IsReusable  {   get   {    return false;   }  } }}


最後就是ASP.NET頁面圖片路徑的引用了

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SecurityCode_Test.aspx.cs" Inherits="SecurityCodePic.SecurityCode_Test" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>驗證碼的實現</title> <style type="text/css"> #VCodeImg { cursor: pointer;} </style></head><body> <form id="form1" runat="server"> <div> <img id="VCodeImg" src="SecurityCode.ashx" alt="驗證碼" onclick="javascript:RefreshCode();" /> </div> </form> <script type="text/javascript">  function RefreshCode() {   var random = Math.random();   var img = document.getElementById("VCodeImg");   img.src = "SecurityCode.ashx?" + random; //加上無意義的隨機參數,瀏覽器才會認為是新地址,就會重新讀取資料  } </script></body></html>

以上就是本文的全部,對了,還有源碼下載分享給大家,歡迎大家下載。

源碼分享:ASP.NET驗證碼實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.