点滴积累【C#】---验证码,ajax提交

8/3/2015来源:C#应用人气:2666

点滴积累【C#】---验证码Ajax提交

效果:

思路:

借用ashx文件创建四位验证,首先生成四位随机数字。然后创建画布,再将创建好的验证码存入session,然后前台进行button按钮将文本框中的值进行ajax请求到后台,和session中的验证码进行对比,成功返回true,失败返回false.

代码:

【前台】

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="verifycodeDemo.aspx.cs" Inherits="verifycodeDemo.verifycodeDemo" %> 2  3 <!DOCTYPE html> 4  5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 8     <title>青苹果验证码例子</title> 9     <script src="jquery-1.3.2.min.js"></script>10     <script type="text/javascript">11         //切换验证码12         function ToggleCode(obj, codeurl) {13             $("#" + obj).attr("src", codeurl + "?time=" + Math.random());14         }15         //ajax提交后台验证16         function postAjax() {17             var VerifyCodeValue = $("#txtVerifyCode").val();18             $.ajax({19                 type: 'post',20                 dataType: "text",21                 url: "verifycodeDemo.aspx",22                 data: "action=comparison&VerifyCode=" + VerifyCodeValue,23                 cache: false,24                 async: false,25                 success: function (msg) {26                     if (msg == "false") {27                         alert("验证失败!sorry,青苹果");28                         ToggleCode("Verify_codeImag", "VerifyCode.ashx");29                         $("#txtVerifyCode").val("");30                     }31                     else {32                         alert("验证成功!hello,青苹果!");33                     }34                 }35             });36         }37     </script>38 </head>39 <body>40     <form id="form1" runat="server">41         <div>42             <input type="text" id="txtVerifyCode" />43             <img src="VerifyCode.ashx" id="Verify_codeImag" alt="点击切换验证码" style="CURSOR: pointer" width="65" height="25" title="点击切换验证码" onclick="ToggleCode(this.id, 'VerifyCode.ashx');return false;" />44             <input type="button" value="青苹果验证码" onclick="postAjax()" />45         </div>46     </form>47 </body>48 </html>

【后台】

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7  8 namespace verifycodeDemo 9 {10     public partial class verifycodeDemo : System.Web.UI.Page11     {12         PRotected void Page_Load(object sender, EventArgs e)13         {14             string action = Request.Params["action"];15             string VerifyCodeValue = Request.Params["VerifyCode"];16             if (action == "comparison")17             {18                 string Msg = "true";19                 //对session中存储的验证码对比20                 if (HttpContext.Current.Session["dt_session_code"] == null || VerifyCodeValue.ToLower() != HttpContext.Current.Session["dt_session_code"].ToString().ToLower())21                 {22                     Msg = "false";//验证码输入不正确23                 }24                 Response.Write(Msg);25                 Response.End();26             }27 28         }29     }30 }

【ashx文件】

  1 using System;  2 using System.Collections.Generic;  3 using System.Drawing;  4 using System.Drawing.Imaging;  5 using System.IO;  6 using System.Linq;  7 using System.Web;  8 using System.Web.SessionState;  9  10  11 namespace ESoftMS.Web.Frame 12 { 13     /// <summary> 14     /// VerifyCode 的摘要说明 青苹果(www.cnblogs.com/xinchun) 15     /// </summary> 16     public class VerifyCode : IHttpHandler, IRequiresSessionState 17     { 18  19         public void ProcessRequest(HttpContext context) 20         { 21             int codeW = 80; 22             int codeH = 22; 23             int fontSize = 16; 24             string chkCode = string.Empty; 25             //颜色列表,用于验证码、噪线、噪点  26             Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue }; 27             //字体列表,用于验证码  28             string[] font = { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" }; 29             //验证码的字符集,去掉了一些容易混淆的字符  30             char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' }; 31             Random rnd = new Random(); 32             //生成验证码字符串  33             for (int i = 0; i < 4; i++) 34             { 35                 chkCode += character[rnd.Next(character.Length)]; 36             } 37             //写入Session 38             context.Session["dt_session_code"] = chkCode; 39             //创建画布 40             Bitmap bmp = new Bitmap(codeW, codeH); 41             Graphics g = Graphics.FromImage(bmp); 42             g.Clear(Color.White); 43             //画噪线  44             for (int i = 0; i < 1; i++) 45             { 46                 int x1 = rnd.Next(codeW); 47                 int y1 = rnd.Next(codeH); 48                 int x2 = rnd.Next(codeW); 49                 int y2 = rnd.Next(codeH); 50                 Color clr = color[rnd.Next(color.Length)]; 51                 g.DrawLine(new Pen(clr), x1, y1, x2, y2); 52             } 53             //画验证码字符串  54             for (int i = 0; i < chkCode.Length; i++) 55             { 56                 string fnt = font[rnd.Next(font.Length)]; 57                 Font ft = new Font(fnt, fontSize); 58                 Color clr = color[rnd.Next(color.Length)]; 59                 g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 + 2, (float)0); 60             } 61             ////画噪点  62             //for (int i = 0; i < 1; i++) 63             //{ 64             //    int x = rnd.Next(bmp.Width); 65             //    int y = rnd.Next(bmp.Height); 66             //    Color clr = color[rnd.Next(color.Length)]; 67             //    bmp.SetPixel(x, y, clr); 68             //} 69             //清除该页输出缓存,设置该页无缓存  70             context.Response.Buffer = true; 71             context.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0); 72             context.Response.Expires = 0; 73             context.Response.CacheControl = "no-cache"; 74             context.Response.AppendHeader("Pragma", "No-Cache"); 75             //将验证码图片写入内存流,并将其以 "image/Png" 格式输出  76             MemoryStream ms = new MemoryStream(); 77             try 78             { 79                 bmp.Save(ms, ImageFormat.Png); 80                 context.Response.ClearContent(); 81                 context.Response.ContentType = "image/Gif"; 82                 context.Response.BinaryWrite(ms.ToArray()); 83             } 84             catch (Exception) 85             { 86  87             } 88             finally 89             { 90                 g.Dispose(); 91                 bmp.Dispose(); 92             } 93         } 94  95         public bool IsReusable 96         { 97             get 98             { 99                 return false;100             }101         }102     }103 }

Demo下载:

http://files.cnblogs.com/xinchun/verifycodeDemo.rar