产生随机验证码(asp.net)

当用户点击验证码时,会发生改变,效果如图

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;
            }
        }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值