在vs2005中可以直接创建.ashx文件,其项目叫做一般处理程序,.ashx文件一般用来处理只有返回,二一般不回传的数据,比如动态生成图片,或者文字,以下为清清月儿博客上转载的一个用ashx动态生成验证码图片的代码。
//绘制验证码图片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, IRequiresSessionState14 { 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 - 1].ToString(), font, new SolidBrush(Color.Blue), i * 38, r.Next(0, 15));45 }46 47 //生成干扰线条48 Pen pen = new Pen(new SolidBrush(Color.Blue), 2);49 for (int i = 0; i < 10; i++)50 { 51 g.DrawLine(pen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));52 }53 b.Save(hc.Response.OutputStream, ImageFormat.Gif);54 hc.Session[strIdentify] = s.ToString(); //先保存在Session中,验证与用户输入是否一致55 hc.Response.End();56 57 }58 59 /// <summary>60 /// 表示此类实例是否可以被多个请求共用(重用可以提高性能)61 /// </summary>62 public bool IsReusable63 { 64 get65 { 66 return true;67 }68 }69 }//前台代码中引用ashx文件
.....
<img width="100px" height="25px" src="ValidateImageHandler.ashx"/>
....
这里因为使用的是默认 *.asah处理文件类型,在machine.config文件中已经有此类型的默认注册,
因为这里不需要注册
1 <httpHandlers> 2 <add verb="*" path="*.asah" type="System.Web.UI.SimpleHandlerFactory" /> 3 </httpHandlers> 4
注意:
1.再注册一下也不会出错,会覆盖machine.config文件配置
2.如果在同一个配置文件中注册多次,默认后者也会覆盖前者.
3.如果其它格式(系统默认没有注册)的,务必要在Web.config文件中注册一下.
本文转自齐师傅博客园博客,原文链接:http://www.cnblogs.com/youring2/archive/2009/04/03/1428661.html,如需转载请自行联系原作者