httphandler生成无刷新验证码图片

首先添加一个handler<br />
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
public class Handler : IHttpHandler,IRequiresSessionState
{
   
    public void ProcessRequest (HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
       
        Bitmap basemap = new Bitmap(200, 60);
        Graphics graph = Graphics.FromImage(basemap);
        graph.FillRectangle(new SolidBrush(Color.White),0,0,200,60);
        Font font = new Font(FontFamily.GenericSansSerif,48,FontStyle.Bold,GraphicsUnit.Pixel);
        Random r = new Random();
        string letters = "abcdefghijklmnopqrstuvwxyz1234567890";
        string letter;
        StringBuilder s = new StringBuilder();
 
        for (int i = 0; i < 5; i++)
        {
            letter = letters.Substring(r.Next(0,letters.Length-1),1);
            s.Append(letter);
            graph.DrawString(letter,font,new SolidBrush(Color.Blue),i*38,r.Next(0,15));
        }
               
        Pen linePen = new Pen(new SolidBrush(Color.Brown),2);
        for (int i = 0; i < 6; i++)
        {
            graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
          
        }
        basemap.Save(context.Response.OutputStream, ImageFormat.Gif);
        context.Session["CheckCode"] = s.ToString();
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return true;
        }
    }
}
这是生成图片的代码。
然后在引用这个handler就可以了。

<img id="imgCheckCode" style="cursor:pointer" src="handler.ashx" alt="看不清?点击更换" onclick="this.src=this.src+'?'"/ />

但是我对onclick="this.src=this.src+'?'"这里不了解,这个+'?'什么作用呢?闷纳。
这样就实现了无数新验证码的功能了,这只是简单的实现,具体应用的需要按照需求来做进一步处理了。

这几天再看关于HttpHandler和HttpModule的内容,因此仿照别人的东西自己也动手写了一下,非原创,只是记录下来,希望对自己和别人能有点帮助。

HttpHandler和HttpModule的内容我暂时还不能讲解,免得误人子弟,我也只是刚刚了解一点,仍需要继续努力。如果大家想学习HttpHandler和HttpModule的话请参考:
http://www.theserverside.net/tt/articles/showarticle.tss?id=IIS_ASP

posted @ 2008-01-02 13:01  pysharp  阅读(791)  评论(4编辑  收藏  举报