这是后台的代码VerifyCode.ashx.cs /// <summary> /// 验证码 /// </summary> public class VerifyCode : IHttpHandler, IRequiresSessionState { public static bool Validate(string code) { return string.Compare(code, Code.Replace(" ",""), true) == 0; } static string Code { get { var obj = HttpContext.Current.Session["verifyCode"]; if (obj == null) return string.Empty; return obj.ToString(); } set { HttpContext.Current.Session["verifyCode"] = value; } } public void ProcessRequest(HttpContext context) { char[] source = ("ABCDEFGHIJKLMNPQRSTUVWXYZ123456789").ToCharArray(); Random random = new Random(); string text = ""; for (int i = 0; i < 4; i++)//4 { text += source[random.Next(0, source.Length)] + " "; } text = text.Trim(); Code = text; //save in server for authenticate Bitmap CodePic = new Bitmap(65, 20); Graphics oGraphics = Graphics.FromImage(CodePic); SolidBrush oBrushForBack = new SolidBrush(Color.WhiteSmoke); oGraphics.FillRectangle(oBrushForBack, 0, 0, CodePic.Width, CodePic.Height);//将位图刷色 oBrushForBack.Dispose(); //画背景线 for (int i = 0; i < 60; i++) { int x1 = random.Next(60); int x2 = random.Next(60); int y1 = random.Next(20); int y2 = random.Next(20); float f=float.Parse(random.Next(4).ToString()); oGraphics.DrawLine(new Pen(Color.FromArgb(random.Next()),f), x1, y1, x2, y2); } FontStyle eFontStyle = FontStyle.Bold;//字体样式 int iFontSize = 11; string sColor = "Blue"; StringAlignment eAlign = StringAlignment.Center; Rectangle oRect = new Rectangle(2, 0, CodePic.Width, CodePic.Height); Font oFont = new Font("Arial", iFontSize, eFontStyle); StringFormat oFormat = new StringFormat();//字符串格式 oFormat.Alignment = eAlign;//设置字符串格式 oFormat.LineAlignment = StringAlignment.Center;//设置字符串格式 SolidBrush oBrush = new SolidBrush(Color.FromName(sColor)); oGraphics.DrawString(text, oFont, oBrush, oRect, oFormat); oBrush.Dispose(); //画图片的前景噪音点 for (int i = 0; i < 60; i++) { int x = random.Next(60); int y = random.Next(20); CodePic.SetPixel(x, y, Color.FromArgb(random.Next())); } HttpContext.Current.Response.ContentType = "image/gif"; HttpContext.Current.Response.ClearContent(); CodePic.Save(HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif); oGraphics.Dispose(); CodePic.Dispose(); } 其他页面调用验证码如下: <li class="verify"> <asp:Image ID="imgVerifyCode" runat="server" ImageUrl="/VerifyCode.ashx" align="absmiddle" /> <a href="#" mce_href="#" οnclick="return reloadImg('imgVerifyCode');"> <img src="../Images/hip_reload.gif" mce_src="Images/hip_reload.gif" border="0" align="middle"></a> </li> <mce:script type="text/javascript" language="javascript"><!-- function reloadImg(id) { var obj = $("#<%=imgVerifyCode.ClientID%>"); var src = obj.attr("src"); var pos = src.indexOf('?'); if (pos >= 0) { src = src.substr(0, pos); } var date = new Date(); obj.attr("src", src + '?v=' + date.getTime()); //obj.src = return false; } // --></mce:script>