webform 验证码

在webform中写验证码必须先建一个一般处理程序。

public class Handler : IHttpHandler ,IRequiresSessionState//session接口 { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "image/Jpeg"; string charSet = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y"; string[] CharArray = charSet.Split(','); string code = ""; int temp = -1; Random rand1 = new Random(); for (int j = 0; j < 4; j++) { if (temp != -1) { rand1 = new Random(j * temp * ((int)DateTime.Now.Ticks)); } int t = rand1.Next(CharArray.Length - 1); if (temp == t) { return; } temp = t; code += CharArray[t]; } context.Session["yanzhen"]=code; System.Drawing.Bitmap image = new System.Drawing.Bitmap(50, 23); Graphics g = Graphics.FromImage(image); Font f = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold)); // 前景色 Brush b = new System.Drawing.SolidBrush(Color.Black); // 背景色 g.Clear(Color.White); // 填充文字 g.DrawString(code, f, b, 0, 1); // 随机线条 Pen linePen = new Pen(Color.Gray, 0); Random rand = new Random(); for (int i = 0; i < 5; i++) { int x1 = rand.Next(image.Width); int y1 = rand.Next(image.Height); int x2 = rand.Next(image.Width); int y2 = rand.Next(image.Height); g.DrawLine(linePen, x1, y1, x2, y2); } // 随机点 for (int i = 0; i < 30; i++) { int x = rand.Next(image.Width); int y = rand.Next(image.Height); image.SetPixel(x, y, Color.Gray); } // 边框 g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1); // 输出图片 System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); context.Response.ClearContent(); context.Response.BinaryWrite(ms.ToArray()); }

再用简单的ajax异步操作刷新

function ajax(url,success) {
    var xmlrequest = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    xmlrequest.open("POST", url, true);
    xmlrequest.onreadystatechange() = function () {
        if (xmlrequest.readyState==4) {
            if (xmlrequest.status == 200) {
                success(xmlrequest.responseText);
            }
            else {
                alert("Action错误!");
            }
        }
    }
    xmlrequest.send();
}

原文地址:https://www.cnblogs.com/lushixiong/p/4661309.html