验证码的页面可能由于验证码不清楚,单击需要获得新的验证码
服务器端用C#实现如下:
/// <summary> /// 验证码类,用于生成验证码 /// </summary> public static class ValidateCode { private static string CreateRandomCode(int codeCount) { string allChar = "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,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(i * temp * ((int)DateTime.Now.Ticks)); } int t = rand.Next(35); if (temp == t) { return CreateRandomCode(codeCount); } temp = t; randomCode += allCharArray[t]; } return randomCode; } public static MemoryStream CreateImage(out string checkCode) { //生成随机数 checkCode = CreateRandomCode(4); int iwidth = (int)(checkCode.Length * 13.5); System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20); Graphics g = Graphics.FromImage(image); Font f = new System.Drawing.Font("Arial", 12, System.Drawing.FontStyle.Bold); Brush b = new System.Drawing.SolidBrush(Color.Black); //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height); g.Clear(Color.White); g.DrawString(checkCode, f, b, 3, 3); Pen blackPen = new Pen(Color.Black, 0); Random rand = new Random(); for (int i = 0; i < 3; i++) { int y = rand.Next(image.Height); g.DrawLine(blackPen, 0, y, image.Width, y); } MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); g.Dispose(); image.Dispose(); return ms; } } [/code] 使用Asp.net MVC实现的Controller调用验证码的Action如下: 没有生成中间gif,jpg文件 [code] /// <summary> /// 获得验证码 /// </summary> public void GetValidateCode() { try { //生成验证码 string validateCode; Session["ValidateCode"] = ""; //生成验证码图片 MemoryStream ms = ValidateCode.CreateImage(out validateCode); ViewData["Code"] = ms; //保存到Session Session["ValidateCode"] = validateCode; Response.ClearContent(); Response.ContentType = "image/Gif"; Response.BinaryWrite(ms.ToArray()); } catch (Exception e) { Response.Write("验证码生成失败!错误消息:" + e.Message); } }
页面代码:
<script language="javascript" type="text/javascript"> //获得验证码 function GetCode() { //注意后面一定要加随机数,这样<img>才能更新为新的验证码 $("#validateImg").attr("src","/user/GetValidateCode?sd="+Math.random()); } </script> <a id="getCode" href="javascript:GetCode();"><img id="validateImg" src="/user/GetValidateCode" alt="点击获得验证码" /></a>