效果:

思路:
借用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="點擊切換驗證碼" 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.Page
11 {
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
點滴積累方有為應該
是“力”
近義詞 積少成多、集腋成裘、聚沙成塔 反義詞 一曝十寒
寸積铢累 ( cùn jī zhū lěi ) 解 釋 铢:古計量單位,24铢為一兩(1斤=16兩);累:積累。
形容點點滴滴地積累