当用户点击验证码时,会发生改变,效果如图
aspx中body内的代码,注意<img>标签
<body>
<form id="form1" runat="server">
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td>用户名:</td>
<td><asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>密码:</td>
<td><asp:TextBox ID="txtPassword" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>验证码:</td>
<td><input type="text" /><img src="~/admin/ashx/ValidateCode.ashx" runat="Server" alt="验证码" title="看不清,换一个" οnclick="this.src='./ashx/ValidateCode.ashx?random='+new Date().getSeconds();"/></td>
</tr>
<tr>
<td>
<asp:Button ID="btnLogin" runat="server" Text="登录" />
</td>
<td>
<asp:Button ID="btnCancel" runat="server" Text="取消" />
</td>
</tr>
</table>
</form>
</body>
一般处理程序ValidateCode.ashx中主要代码
public class ValidateCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/JPEG"; //创建图片 using(System.Drawing.Bitmap bm = new System.Drawing.Bitmap(52,21)) { //创建一个画布 using(System.Drawing.Graphics gp = System.Drawing.Graphics.FromImage(bm)) { string strCode = FuncHelper.GetRandomCode(4); //将验证码写入Session中以备校验 HttpContext.Current.Session["CheckCode"] = strCode; gp.Clear(System.Drawing.Color.FromArgb(231,171,47)); gp.DrawString(strCode, new System.Drawing.Font("宋体", 16), System.Drawing.Brushes.Green, new System.Drawing.PointF(0, 0)); System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Brushes.Blue,2); gp.DrawEllipse(pen, new System.Drawing.Rectangle(2, 2, 40, 18)); //将图片保存到回发的输出流中 bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } } public bool IsReusable { get { return false; } } }