学习整理了一下
(一).功能
用HttpHandler实现图片验证码
![](https://p-blog.csdn.net/images/p_blog_csdn_net/ChengKing/ValidateImageHttpHandler.jpg)
(二).代码如下
1. 处理程序文件 ValidateImageHandler.ashx代码如下
1
<%
@ WebHandler Language
=
"
C#
"
Class
=
"
ValidateImageHandler
"
%>
2
3 using System;
4 using System.Web;
5 using System.Web.SessionState;
6 using System.Drawing;
7 using System.Drawing.Imaging;
8 using System.Text;
9
10 /// <summary>
11 /// ValidateImageHandler 生成网站验证码功能
12 /// </summary>
13 public class ValidateImageHandler : IHttpHandler, IRequiresSessionState
14 {
15 int intLength = 5 ; // 长度
16 string strIdentify = " Identify " ; // 随机字串存储键值,以便存储到Session中
17 public ValidateImageHandler()
18 {
19 }
20
21 /// <summary>
22 /// 生成验证图片核心代码
23 /// </summary>
24 /// <param name="hc"></param>
25 public void ProcessRequest(HttpContext hc)
26 {
27 // 设置输出流图片格式
28 hc.Response.ContentType = " image/gif " ;
29
30 Bitmap b = new Bitmap( 200 , 60 );
31 Graphics g = Graphics.FromImage(b);
32 g.FillRectangle( new SolidBrush(Color.YellowGreen), 0 , 0 , 200 , 60 );
33 Font font = new Font(FontFamily.GenericSerif, 48 , FontStyle.Bold, GraphicsUnit.Pixel);
34 Random r = new Random();
35
36 // 合法随机显示字符列表
37 string strLetters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 " ;
38 StringBuilder s = new StringBuilder();
39
40 // 将随机生成的字符串绘制到图片上
41 for ( int i = 0 ; i < intLength; i ++ )
42 {
43 s.Append(strLetters.Substring(r.Next( 0 , strLetters.Length - 1 ), 1 ));
44 g.DrawString(s[s.Length -
2
3 using System;
4 using System.Web;
5 using System.Web.SessionState;
6 using System.Drawing;
7 using System.Drawing.Imaging;
8 using System.Text;
9
10 /// <summary>
11 /// ValidateImageHandler 生成网站验证码功能
12 /// </summary>
13 public class ValidateImageHandler : IHttpHandler, IRequiresSessionState
14 {
15 int intLength = 5 ; // 长度
16 string strIdentify = " Identify " ; // 随机字串存储键值,以便存储到Session中
17 public ValidateImageHandler()
18 {
19 }
20
21 /// <summary>
22 /// 生成验证图片核心代码
23 /// </summary>
24 /// <param name="hc"></param>
25 public void ProcessRequest(HttpContext hc)
26 {
27 // 设置输出流图片格式
28 hc.Response.ContentType = " image/gif " ;
29
30 Bitmap b = new Bitmap( 200 , 60 );
31 Graphics g = Graphics.FromImage(b);
32 g.FillRectangle( new SolidBrush(Color.YellowGreen), 0 , 0 , 200 , 60 );
33 Font font = new Font(FontFamily.GenericSerif, 48 , FontStyle.Bold, GraphicsUnit.Pixel);
34 Random r = new Random();
35
36 // 合法随机显示字符列表
37 string strLetters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 " ;
38 StringBuilder s = new StringBuilder();
39
40 // 将随机生成的字符串绘制到图片上
41 for ( int i = 0 ; i < intLength; i ++ )
42 {
43 s.Append(strLetters.Substring(r.Next( 0 , strLetters.Length - 1 ), 1 ));
44 g.DrawString(s[s.Length -