很多网站在登录的时候都需要填写一个验证码,目的是避免用户恶意登录或者通过不断模拟用户登录来破译用户密码。所以就有了登录验证码。
实现方式比较简单。验证码图片是由程序绘出来的,并且随机生成的文字并且保存在Session中,用户在界面中输入图片中的问题,发送到服务端与Session中的验证码比较,如果正确就继续,不正确就通知用户并刷新验证码图片。
好了,上代码。
Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Login" %> <!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> <link rel="Stylesheet" type="text/css" href="css/emx_nav_left.css" /> <script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.js"></script> </head> <body> <div id="login"> <table cellpadding="0" cellspacing="0" border="0" style="width: 400px"> <tr> <td> <span>账号</span> </td> <td> <input type="text" style="width: 150px" id="UserAccount" /> </td> </tr> <tr> <td> <span>密码</span> </td> <td> <input type="password" style="width: 150px" id="Password" /> </td> </tr> <tr> <td> <span>验证码</span> </td> <td> <input type="text" id="textValidateCode" maxlength="5" style="width: 50px;" /><img src="" alt="点击刷新" id="imgValidateCode" style="width:100px; height:40px;line-height:30px;vertical-align:middle;" /> </td> </tr> <tr> <td colspan="2"> <div style="margin-left: 42px"> <input type="button" value="登录" οnclick="return Login();" style="background-image: url('/img/btn.gif'); border-style: none; color: White; width: 70px; height: 26px;" /> <input type="button" value="重置" οnclick="return Reset();" style="background-image: url('/img/btn.gif'); border-style: none; color: White; width: 70px; height: 26px;" /> </div> </td> </tr> </table> </div> <script language="javascript" type="text/javascript"> function DoFresh() { var img = document.getElementById("imgValidateCode"); img.src = "/form/VerifyCode.aspx?random=" + Math.random(); } document.onkeydown = function (event) { var e = event || window.event || arguments.callee.caller.arguments[0]; if (e && e.keyCode == 13) { Login(); } }; jQuery(document).ready(function () { $("#UserAccount").focus(); $("#imgValidateCode").click(function () { DoFresh(); }); DoFresh(); }); function Login() { var user = jQuery.trim($("#UserAccount").val()); var pwd = jQuery.trim($("#Password").val()) var validateCode = jQuery.trim($("#textValidateCode").val()) if (user.length == 0 || pwd.length == 0) { alert('请输入用户名和密码'); return false; } else { jQuery.ajax({ type: "POST", dataType: "json", url: "/Login.aspx?method=userlogin", data: { UserAccount: user, Password: pwd, ReturnUrl: ‘’, ValidateCode: validateCode }, success: function (data) { if (data.loginResult != "validcodewrong") { } else { alert('验证码错误'); DoFresh(); return false; } }, error: function (msg) { alert('系统异常,请稍后重试'); return false; } }); } } function Reset() { $("#UserAccount").val(""); $("#Password").val(""); $("#textValidateCode").val(""); return false; } </script> </body> </html>
VerifyCode.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="VerifyCode.aspx.cs" Inherits="VerifyCode" %> <!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> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
VerifyCode.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; namespace Form { public partial class VerifyCode : System.Web.UI.Page { public static string HZ; /// <summary> /// 验证码的最大长度 /// </summary> public int MaxLength { get { return 10; } } /// <summary> /// 验证码的最小长度 /// </summary> public int MinLength { get { return 1; } } protected void Page_Load(object sender, EventArgs e) { string[] str = CreateValidateNumber(5); string strcode = string.Empty; for (int i = 0; i < str.Length; i++) { strcode += str[i]; } CreateCheckCodeImage(str); HZ = strcode; Response.Write(HZ); //验证码存入session Session["ValidateCode"] = HZ; } /// <summary> /// 生成验证码 /// </summary> /// <param name="length">指定验证码的长度</param> /// <returns>验证码</returns> public string[] CreateValidateNumber(int length) { string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p" + ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q" + ",R,S,T,U,V,W,X,Y,Z"; string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分成数组 string[] num = new string[length]; int temp = -1;//记录上次随机数值,尽量避避免生产几个一样的随机数 Random rand = new Random(); //采用一个简单的算法以保证生成随机数的不同 for (int i = 1; i < length + 1; i++) { if (temp != -1) { rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks)); } int t = rand.Next(61); if (temp != -1 && temp == t) { return CreateValidateNumber(length); } temp = t; num[i - 1] = VcArray[t]; //num.SetValue(VcArray[t]); //VNum += VcArray[t]; } return num; } private void CreateCheckCodeImage(string[] checkCode) { if (checkCode == null || checkCode.Length <= 0) return; System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 32.5)), 60); System.Drawing.Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //定义颜色 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; //画图片的背景噪音线 for (int i = 0; i < 25; i++) { int cindex = random.Next(7); int findex = random.Next(5); 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(c[cindex]), x1, y1, x2, y2); } //定义字体 string[] f = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; for (int k = 0; k <= checkCode.Length - 1; k++) { int cindex = random.Next(7); int findex = random.Next(5); Font drawFont = new Font(f[findex], 26, (System.Drawing.FontStyle.Bold)); SolidBrush drawBrush = new SolidBrush(c[cindex]); float x = 5.0F; float y = 0.0F; float width = 42.0F; float height = 48.0F; int sjx = random.Next(10); int sjy = random.Next(image.Height - (int)height); RectangleF drawRect = new RectangleF(x + sjx + (k * 25), y + sjy, width, height); StringFormat drawFormat = new StringFormat(); drawFormat.Alignment = StringAlignment.Center; g.DrawString(checkCode[k], drawFont, drawBrush, drawRect, drawFormat); } //画图片的前景噪音点 for (int i = 0; i < 500; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } int cindex1 = random.Next(7); //画图片的边框线 g.DrawRectangle(new Pen(c[cindex1]), 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(); } } } }