一個簡單的驗證碼的例子
下面是一個簡單的實現驗證碼的例子,包括生成驗證碼,JavaScript非同步呼叫驗證,超時,等,程式碼很簡單,稍微看看就可以明白
在網上搜了很多例子,總結如下
生成隨機圖片,這個是在網上找的原始碼,新建一個網頁,在page_load里加如下程式碼,Identity是驗證時session的關鍵字Key,我取的是遠端IP和時間戳,這樣在驗證的時候保證唯一性
protected void Page_Load(object sender, EventArgs e)
{
string chkCode = string.Empty;
//顏色列表,用於驗證碼、噪線、噪點
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
//字型列表,用於驗證碼
string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };
//驗證碼的字符集,去掉了一些容易混淆的字元
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
Random rnd = new Random();
//生成驗證碼字串
for (int i = 0; i <4; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
Session[Identity] = chkCode;
Response.Cookies.Add(new HttpCookie(Identity, chkCode));
Bitmap bmp = new Bitmap(100, 40);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
//畫噪線
for (int i = 0; i < 10; i++)
{
int x1 = rnd.Next(100);
int y1 = rnd.Next(40);
int x2 = rnd.Next(100);
int y2 = rnd.Next(40);
Color clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
//畫驗證碼字串
for (int i = 0; i < chkCode.Length; i++)
{
string fnt = font[rnd.Next(font.Length)];
Font ft = new Font(fnt, 18);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 8, (float)8);
}
//畫噪點
for (int i = 0; i < 100; i++)
{
int x = rnd.Next(bmp.Width);
int y = rnd.Next(bmp.Height);
Color clr = color[rnd.Next(color.Length)];
bmp.SetPixel(x, y, clr);
}
//清除該頁輸出快取,設定該頁無快取
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
//將驗證碼圖片寫入記憶體流,並將其以 "image/Png" 格式輸出
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
}
finally
{
//顯式釋放資源
bmp.Dispose();
g.Dispose();
}
}
呼叫這個隨機碼
再新建一個頁面,在頁面上加一個image控制元件,通過JavaScript來指定圖片的src為剛才生成隨機碼的頁面,加一個輸入框,輸入驗證碼,加一個linkbutton,當看不清的時候換一張,放一個button,當單擊的時候驗證輸入是否合法,
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
<asp:Image ID="imgURL" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="LoadPage();return false">看不清,換一張</asp:LinkButton>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Test();return false" />
</td>
</tr>
</table>
</div>
</form>
<script type="text/javascript" language="javascript">
var Identity = '<%=Identity %>' + new Date().toLocaleString();
var xmlHttp;
function LoadPage() {
// alert(new Date().toGMTString());
var img = document.getElementById("<%=imgURL.ClientID %>");
Identity = '<%=Identity %>' + new Date().toLocaleTimeString();
img.src = "ValidateKey.aspx?Identity=" + Identity;
}
function createXMLRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLRequest) {
xmlHttp = new XMLHttpRequest;
} else {
alert("不能建立");
}
}
function Test() {
createXMLRequest(); //呼叫建立XMLRequest的方法
xmlHttp.onreadystatechange = handleStatechange;
var txtCode = document.getElementById("<%=txtCode.ClientID %>");
xmlHttp.open("GET", "ValidateKey_Validate.ashx?chkCode=" + txtCode.value + "&Identity=" + Identity, false);
xmlHttp.send(null);
}
function handleStatechange() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (xmlHttp.responseText != "驗證碼通過") {
LoadPage();
}
alert(xmlHttp.responseText);
}
}
LoadPage();
</script>
在按鈕的Test函式裡通過Ajax非同步驗證來驗證顯示圖片和輸入是否一致,
新建一個ashx檔案,在這裡非同步驗證是否一致,這裡需要注意的是必須實現IRequiresSessionState介面,否則無法使用session。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace WebProject
{
/// <summary>
/// Summary description for ValidateKey_Validate
/// </summary>
public class ValidateKey_Validate : IHttpHandler,
IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string returnValue = "錯誤異常";
string chkCode = "";
if (string.IsNullOrEmpty(context.Request.QueryString["chkCode"]) == false)
{
chkCode = context.Request.QueryString["chkCode"].ToString();
}
if (chkCode == "")
{
returnValue = "請輸入驗證碼";
}
else
{
string identity = "";
string createCode = "";
if (string.IsNullOrEmpty(context.Request.QueryString["Identity"]) == false)
{
identity = context.Request.QueryString["Identity"].ToString();
if (context.Session[identity] != null)
{
createCode = context.Session[identity].ToString();
}
}
if ( createCode != "" && identity != "")
{
DateTime createDate = DateTime.MinValue;
string[] idenitityValue = identity.Split('_');
if (idenitityValue != null && idenitityValue.Length > 1)
{
DateTime.TryParse(idenitityValue[1], out createDate);
if (DateTime.Now - createDate > TimeSpan.FromSeconds(10))
{
returnValue = "驗證碼超期";
}
else
{
if (createCode.ToLower() != chkCode.ToLower())
{
returnValue = "驗證碼不對";
}
else
{
returnValue = "驗證碼通過";
}
}
}
}
}
context.Response.ContentType = "text/plain";
context.Response.Write(returnValue);
}
public bool IsReusable
{
get
{
return false;
}
}
}