程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net 驗證碼生成和刷新及驗證

asp.net 驗證碼生成和刷新及驗證

編輯: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 頁面引用:
<asp:Image ID="getcode" src="VerifyCode.aspx" runat="server" />
一般需要同時提供刷新功能(看不清楚換一張),代碼如下
<asp:Image ID="getcode" src="VerifyCode.aspx" runat="server" />  <A href="javascript:getimgcode()">刷新驗證碼</A>
如使用了母版頁,則用如下代碼:
<img ID="getcode" alt="" src="VerifyCode.aspx" /> <%--<asp:Image ID="getcode" src="VerifyCode.aspx" runat="server" />--%>
  <A href="javascript:getimgcode()">刷新驗證碼</A>
超鏈接對應的javascript如下:
<script language="javascript" type="text/javascript">
function getimgcode()
{
var getimagecode = document.getElementById("getcode");
getimagecode.src = "VerifyCode.aspx";
}
</script>
3 判斷驗證
上述代碼是將驗證碼存貯在Session中,用code來標志。讀取代碼Session["code"].ToString();
使用中,我們只需要比較Session["code"].ToString()和文本框輸入的串(TextBoxCode.Text)是否相同即可進行判斷。
if(Session["code"].ToString().Trim().Equals(TextBoxCode.Text.Trim()))
...{
Response.Write("Success");
}
測試通過! 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved