验证码是为了防止通过程序的方式,自动去填写信息,然后自动发送给Web服务器而欺骗服务器进行注册或登录。由于验证码每次都是随机产生的,所以需要人工识别去输入并验证,从而杜绝有人用软件方式自动大量注册ID,从而非法发布广告;或者用于防止对密码的暴力破解。下面教你自己动手写一个验证码。
1. 在你的网站目录下添加一个验证码生成文件:ValidateCode.aspx。
2. 删除该页面所有自动生成的HTML代码,只留下第一行 的页面声明:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidateCode.aspx.cs" Inherits="Default2" %>
3. 在页面ValidateCode.aspx.cs中添加验证码的图像生成代码(添加System.Drawing的引用)
//页面启动时,生成验证码图片
protected void Page_Load(object sender, EventArgs e)
{
string CheckCode = GetRandomCode(4); //得到随机字符串作为验证码
Session["CheckCode"] = CheckCode; //保存验证码变量到Session
SetPageNoCache(); //禁止页面缓存
CreateImage(CheckCode); //创建图片
}
//得到随机字符串
public string GetRandomCode(int CodeCount)
{
string allChar = "A, B, C, D, E,,F, G, H, I, J, A, B, C, D, E, F, G, H, i, J, K, M, N, P, Q, R, S, T, U, W, X, Y, Z";
string[] allCharArray = allChar.Split( ',');
string RandomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < CodeCount; i++)
{
if (temp != -1)
{
rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(33);
while (temp == t)
{
t = rand.Next(33);
}
temp = t;
RandomCode += allCharArray[t];
}
return RandomCode;
}
//为了保证每次显示的生成的图片和内存中实际的验证码一致,要禁止页面缓存
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");
}
//根据得到的随机字符串生成图像
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCode.Length * 14);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 19);
Graphics g = Graphics.FromImage(image);
Font f = new Font("Arial", 10);
Brush b = new System.Drawing.SolidBrush(Color.Black);
Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));
g.Clear(System.Drawing.ColorTranslator.FromHtml("#E5F5FB")); //背景色
char[] ch = checkCode.ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] >= '0' && ch[i] <= '9')
{
//数字用红色显示
g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
}
else
{
//字母用黑色显示
g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
}
}
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.Cache.SetNoStore();
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
4. 调用验证码
当调用验证码时,在使用验证码的页面加入以下代码:
<asp:Label ID="lblGUID" runat="server" Style="display:none" ></asp:Label>
<a id="A2" href="" onclick="ChangeCode(); return false;">
<asp:Image ID="ImageCheck" runat="server" ImageAlign="AbsMiddle"
ImageUrl="ValidateCode.aspx?GUID=GUID" ToolTip="看不清,换一个" /></a>
在Label的onclick事件里面用脚本实现变换验证码:
<script language="javascript" type="text/javascript">
function ChangeCode()
{
var date = new Date();
var myImg = document.getElementById("ImageCheck");
var GUID = document.getElementById("lblGUID");
if (GUID != null)
{
if (GUID.innerHTML != "" && GUID.innerHTML != null)
{
myImg.src = "ValidateCode.aspx?GUID="+GUID.innerHTNL+"&flag="+date.getMilliseconds();
}
}
return false;
}
</script>
5. 在后台代码中验证用户输入的验证码是否正确
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.ViewState["GUID"] = System.Guid.NewGuid().ToString();
this.lblGUID.Text = this.ViewState["GUID"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if ((Session["CheckCode"] != null) && (Session["CheckCode"].ToString() != ""))
{
if (Session["CheckCode"].ToString().ToLower() != this.CheckCode.Text.ToString().ToLower())
{
Session["CheckCode"] = null;
CheckCode.Text = "";
Response.Write("你填写的验证码错误");
return ;
}
else
{
Session["CheckCode"] = null;
}
}
else
{
Response.Redirect("default.aspx");
}
//验证登录的其他代码
}