asp.net中使用一般处理程序生成验证码

生成image-code的代码如下:

<%@ WebHandler Language="C#" Class="ValidCode" %>

using System;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;

public class ValidCode : IHttpHandler, IRequiresSessionState, IReadOnlySessionState{
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/gif";
            Bitmap basemap = new Bitmap(200, 60);
            Graphics garph1 = Graphics.FromImage(basemap);

            garph1.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);

            Random r = new Random();
            string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
            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);
                garph1.DrawString(letter, font, new SolidBrush(Color.Black), i * 38, r.Next(0, 15));

            }

            Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
            for (int x = 0; x < 6; x++)
            {
                garph1.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();    //存入Session,用于对比验证
            context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

调用代码如下:

<img src="AjaxRequest/ValidCode.ashx" alt="" id="code" width="80px" height="25px" onclick="this.src='AjaxRequest/ValidCode.ashx?number='+Math.random()" />

 

posted @ 2012-03-28 14:01  逆水寒龙  阅读(1062)  评论(0编辑  收藏  举报