标签:
建立一个空网站,在设计界面工具箱中拖入一个TextBox工具,一个按钮,外加一个Image图片工具(充当数字、字母以图片形式)。但是这样做出来的验证码会出现一个问题,每当点击一下按钮,界面自动提交一遍,重新刷新一遍再返回,为防止整个页面被重新提交,需要加入一个UpdatePanel,只刷新当前updatePanel内的内容即可。
必须要结合AJAX来使用

界面设计好后,需要添加一个以ashx结尾的文件项,在这里面写位图随机验证码的格式等等。
1 <%@ WebHandler Language="C#" Class="Code" %>
2
3 using System;
4 using System.Web;
5 using System.Drawing;
6 using System.Drawing.Drawing2D;
7 using System.Drawing.Imaging;
8 using System.Web.SessionState;
9 //一般处理程序要使用session,必须要继承IRequiresSessionState接口(接口就是一个空的方法),session存在于这个接口中
10 public class Code : IHttpHandler,IRequiresSessionState {
11
12 public void ProcessRequest (HttpContext context) {
13 context.Response.ContentType = "image/jpeg";
14 Bitmap img = new Bitmap(50, 20);//位图,画了一个空白的图形
15 Graphics g = Graphics.FromImage(img);//
16
17 string s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
18 string str = "";
19 Random rand = new Random();//初始化随机数
20 for (int i = 0; i < 4; i++)
21 {
22 int start = rand.Next(62); //生成一个随机的起始位置
23 str += s.Substring(start, 1).ToString();
24 }
25 context.Session["code"] = str;//session用于传值
26
27 Font font = new Font("宋体",12, FontStyle.Bold);//设置字体格式
28 SolidBrush brush = new SolidBrush(Color.White);
29 g.FillRectangle(brush, 0, 0, 50, 20);
30 brush.Color = Color.Red;
31 g.DrawString(str, font, brush, 0, 0);
32 img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
33 }
34
35 public bool IsReusable {
36 get {
37 return false;
38 }
39 }
40
41 }
一般处理程序:有一个页面A,传递参数到一般处理程序,处理程序接收到参数,访问数据库,判断正确,跳转下一个页面,错误,跳转到另一个页面.
在aspx的Js源代码中,写function语句,确保传递参数
1 <body>
2 <form id="form1" runat="server">
3 <div>
4
5
6 <asp:ScriptManager ID="ScriptManager1" runat="server">
7 </asp:ScriptManager>
8
9 </div>
10 <p>
11 </p>
12
13 <asp:Image ID="Image1" runat="server" ImageUrl="~/Code.ashx" />
14
15 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
16 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
17 <asp:Label ID="Label1" runat="server" Text="失败"></asp:Label>
18 </form>
19 </body>
20 </html>
21 <script>
22 //js方法
23 function changeimg()
24 {
25 var img = document.getElementById("Image1");
26 img.src = "Code.ashx?1=" + Math.random();//使用母版页之后,自己写的ID和JS生成的ID会不一样,需要手动更改ID(方法1)
27 }
28 </script>
29 //方法2:嵌生成之后的ID
30 <script>
31 function changeimg()
32 {
33 var img = document.getElementById("<%=Image1.ClientID%>"); //使用经<% %>转译之后ID
34 img.src = "Code.ashx?1=" + Math.random();
35 }
36 </script>
标签:
原文地址:http://www.cnblogs.com/huaze/p/4302331.html