验证码

一、生成验证码
html代码:

<script type="text/javascript">
    //点击图片更新验证码
    function refreshYZM() {
        //第一种方法,设置src值等于当前时间
        //var imgYZM = document.getElementById("imgYZM");
        //imgYZM.src = "YanZhengMa.ashx?id=" + new Date();
        //第二方法,设置src值每次点击时加1
        $("#imgYZM").attr("src", $("#imgYZM").attr("src") + 1);
    }
</script>

<form action="Cookies.ashx" method="post">
    <table border="1" cellpadding="0" cellspacing="0">
        <tr><td>用户名</td><td><input type="text" name="name" value="@name" /></td></tr>
        <tr><td>密码</td><td><input type="password" name="pwd" value="@pwd" /></td></tr>
        <tr>
            <td><img src="YanZhengMa.ashx?id=1" id="imgYZM" onclick="refreshYZM()" /></td>
            <td><input type="text" name="yzm" /></td>
        </tr>
        <tr><td><input type="submit" name="btnOK" value="登录" /></td><td>@msg</td></tr>
    </table>
</form>

YanZhengMa一般处理程序代码:(可以将验证码保存在cookie或session中)

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "image/jpeg";
    HttpCookie yzm = new HttpCookie("yzm");//创建cookie名称为yzm
    //生成4位随机数
    Random rand = new Random();
    int num = rand.Next(1000, 10000);
    string code = num.ToString();
    yzm.Value = code;//设置浏览器的cookie值为生成的4位随机数
    context.Response.SetCookie(yzm);//将cookie值写入到浏览器
    context.Session["yzm11"] = code;//创建session的值
    //将验证码写入到输出流并显示在浏览器中
    using (Bitmap bmp = new Bitmap(60, 25))
    {
        using (Graphics g = Graphics.FromImage(bmp))
        using (Font font = new Font(FontFamily.GenericSerif, 15))
        {
            g.DrawString(code, font, Brushes.Red, new PointF(0, 0));
        }
        bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
    }
}

获取验证码:(登录时可判断用户输入的验证码与保存在浏览器的验证码相对比)
HttpCookie yzmLogin = context.Request.Cookies["yzm"];//保存在浏览器的验证码
string yzm = yzmLogin.value;

原文地址:https://www.cnblogs.com/genesis/p/4679651.html