验证码
20160204 简单加减乘除验证码
UI
前台UI: <div class="row bg-info"> <form action="Login.ashx" method="post"> <div> <img style="width:80px;height:30px;" src="getpic.ashx"/> </div> <div> <input type="text" name="pic" /><input type="submit" value="提交" /> </div> </form> </div> 后台代码验证: public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; if (context.Request["pic"] != null) { if (context.Request["pic"] == context.Session["pic"].ToString()) context.Response.Write("ok"); else context.Response.Write("no"); } }
类库:
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; //1. creat bitmap using (Image image = new Bitmap(80, 30)) { //2. creat string Graphics g = Graphics.FromImage(image); //3. start draw string g.DrawString(GetString(), new Font("幼圆", 10), Brushes.Yellow, new Point(10, 10)); //4. list pic image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } private string GetString() { Random rd = new Random(); int N1 = rd.Next(10); int N2 = rd.Next(10); int com = rd.Next(3);// 运算符,operator int sum = 0 ; string str = ""; switch (com) { case 0:sum = N1 + N2; str = N1 + " + " + N2 + " = "; break; case 1:sum = N1 - N2; str = N1 + " - " + N2 + " = "; break; case 2:sum = N1 * N2; str = N1 + " × " + N2 + " = "; break; default:str = "error";break; } HttpContext.Current.Session.Add("pic", sum);//生成一个名为session的值 return str; }