首页 > 代码库 > 再学IHanlder 类----------------关于Asp.net与iis原理网上看博客收获写一个验证码用一般处理程序记的好长时间前就写过不过现在再看有点不一样的感觉

再学IHanlder 类----------------关于Asp.net与iis原理网上看博客收获写一个验证码用一般处理程序记的好长时间前就写过不过现在再看有点不一样的感觉

建一个web网站 新建一般处理程序直接贴代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Text;
using System.Drawing.Imaging;

namespace HandlerStudy
{
    /// <summary>
    /// ImageHandler 的摘要说明
    /// </summary>
    public class ImageHandler : IHttpHandler,IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/gif";
            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.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
            Random r = new Random();
            string letters = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string letter = string.Empty;
            StringBuilder s = new StringBuilder();
            //添加随机的五个验证码
            for (int x = 0; x < 5; x++)
            {
                letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
                s.Append(letter);
                graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
            }

            //混淆背景

            Pen linePen = new Pen(new SolidBrush(Color.Black), 2);

            for (int x = 0; x < 8; x++)
            {
                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 false;
            }
        }
    }
}

 

在网页中这样使用:

 

 

 

效果如下: