.net framework 1.1 登录验证码

本文介绍如何使用.ashx文件创建自定义HttpHandler,实现动态验证码的生成,无需处理HTML页面的控件解析和页面处理过程,特别适用于生成动态图片、动态文本等内容。

.ashx 文件用于写web handler的。其实就是带HTML和C#的混合文件。当然你完全可以用.aspx 的文件后缀。使用.ashx 可以让你专注于编程而不用管相关的WEB技术。.ashx必须包含IsReusable. 如下例所示


<% @ webhandler language="C#" class="AverageHandler" %>

using System;
using System.Web;

public class AverageHandler : IHttpHandler
{
public bool IsReusable
{ get { return true; } }
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.Write("hello");
}
}


.ashx比.aspx的好处在与不用多一个html  
注意了VS2005中Web应用程序项目模板里的Generic Handler 项,发现它是一个.ashx文件,实际上它是一个HttpHandler。后来查了一下.Net SDK文档,发现Asp.Net1.1也支持.ashx,但是没有给出详细内容。

我们都知道,HttpHandler是一个彻底自定义Http请求的方法,它通过web.config来定义Asp.Net运行时来过滤出要自定义的Http请求,发送到定义在web.config的指定类中。

利用.ashx文件是一个更好的方法,这个文件类似于.aspx文件,可以通过它来调用HttpHandler类,从而免去了普通.aspx页面的控件解析以及页面处理的过程。这个文件特别适合于生成动态图片,生成动态文本等内容。

1.建立方法如下:
首先打开一个Web项目,然后在任意目录下使用VS2003解决方案资源管理器的“添加”-->“添加新项”,在对话框中选择“文本文件”,然后在文件名处输入“ValidateCode.ashx”。

然后在同目录下,使用解决方案资源管理器,使用“添加”-->“添加类”,在类文件名处输入“ValidateCode.ashx.cs”。可以看出,它的文件命名规律与.aspx文件相同。

然后在.cs文件处输入以下代码(名称空间略):

view plaincopy to clipboardprint?
using System;  
using System.Data;  
using System.Web;  
using System.Collections;  
using System.Web.Services;  
using System.Web.Services.Protocols;  
using System.Drawing;   
using System.Web.SessionState;  
 
 
namespace CodeNamespace  
{  
    /// <summary>  
    /// Summary description for $codebehindclassname$  
    /// </summary>  
    [WebService(Namespace = "http://tempuri.org/")]  
    public class ValidateCode : IHttpHandler,IRequiresSessionState  
    {  
        public void ProcessRequest(HttpContext context)  
        {  
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);///特别注意,如不加,单击验证图片'看不清换一张',无效果.  
            this.CreateCheckCodeImage(GenerateCheckCode(context),context);  
        }   
 
        public bool IsReusable  
        {  
            get 
            {  
                return false;  
            }  
        }  
 
        private string GenerateCheckCode(HttpContext context)  
        {  
            int number;  
            char code;  
            string checkCode = String.Empty;   
 
            System.Random random = new Random();   
 
            for (int i = 0; i < 6; i++)  
            {  
                number = random.Next();   
 
                if (number % 2 == 0)  
                {  
                    code = (char)('0' + (char)(number % 10));  
                }  
                else if (number % 3 == 0)  
                {  
                    code = (char)('A' + (char)(number % 26));  
                }  
                else 
                {  
                    code = (char)('a' + (char)(number % 26));  
                }  
                checkCode += code.ToString();  
            }   
 
            //context.Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));///你也可以存到Seesion里。  
            context.Session.Add("CheckCode",checkCode);  
            //System.Web.HttpContext.Current.Session.Add("CheckCode",checkCode);  
            //System.Web.UI.Page p = new System.Web.UI.Page();  
            //p.Session.Add("CheckCode",checkCode);  
 
            return checkCode;  
        }   
 
        private void CreateCheckCodeImage(string checkCode, HttpContext context)  
        {  
            if (checkCode == null || checkCode.Trim() == String.Empty)  
            {  
                return;   
            }  
 
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);  
            Graphics g = Graphics.FromImage(image);   
 
            try 
            {  
                //生成随机生成器  
                Random random = new Random();   
 
                //清空图片背景色  
                g.Clear(Color.White);   
 
                //画图片的背景噪音线  
                for (int i = 0; i < 25; i++)  
                {  
                    int x1 = random.Next(image.Width);  
                    int x2 = random.Next(image.Width);  
                    int y1 = random.Next(image.Height);  
                    int y2 = random.Next(image.Height);   
 
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);  
                }   
 
                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));  
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);  
                g.DrawString(checkCode, font, brush, 2, 2);   
 
                //画图片的前景噪音点  
                for (int i = 0; i < 100; i++)  
                {  
                    int x = random.Next(image.Width);  
                    int y = random.Next(image.Height);   
 
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));  
                }   
 
                //画图片的边框线  
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);   
 
                System.IO.MemoryStream ms = new System.IO.MemoryStream();  
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);  
                context.Response.ClearContent();  
                context.Response.ContentType = "image/Gif";  
                context.Response.BinaryWrite(ms.ToArray());  
            }  
            finally 
            {  
                g.Dispose();  
                image.Dispose();  
            }   
        }  
    }  

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
using System.Web.SessionState;


namespace CodeNamespace
{
 /// <summary>
 /// Summary description for $codebehindclassname$
 /// </summary>
 [WebService(Namespace = "http://tempuri.org/")]
 public class ValidateCode : IHttpHandler,IRequiresSessionState
 {
  public void ProcessRequest(HttpContext context)
  {
   context.Response.Cache.SetCacheability(HttpCacheability.NoCache);///特别注意,如不加,单击验证图片'看不清换一张',无效果.
   this.CreateCheckCodeImage(GenerateCheckCode(context),context);
  }

  public bool IsReusable
  {
   get
   {
    return false;
   }
  }

  private string GenerateCheckCode(HttpContext context)
  {
   int number;
   char code;
   string checkCode = String.Empty;

   System.Random random = new Random();

   for (int i = 0; i < 6; i++)
   {
    number = random.Next();

    if (number % 2 == 0)
    {
     code = (char)('0' + (char)(number % 10));
    }
    else if (number % 3 == 0)
    {
     code = (char)('A' + (char)(number % 26));
    }
    else
    {
     code = (char)('a' + (char)(number % 26));
    }
    checkCode += code.ToString();
   }

   //context.Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));///你也可以存到Seesion里。
   context.Session.Add("CheckCode",checkCode);
   //System.Web.HttpContext.Current.Session.Add("CheckCode",checkCode);
   //System.Web.UI.Page p = new System.Web.UI.Page();
   //p.Session.Add("CheckCode",checkCode);

   return checkCode;
  }

  private void CreateCheckCodeImage(string checkCode, HttpContext context)
  {
   if (checkCode == null || checkCode.Trim() == String.Empty)
   {
    return;
   }

   System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
   Graphics g = Graphics.FromImage(image);

   try
   {
    //生成随机生成器
    Random random = new Random();

    //清空图片背景色
    g.Clear(Color.White);

    //画图片的背景噪音线
    for (int i = 0; i < 25; i++)
    {
     int x1 = random.Next(image.Width);
     int x2 = random.Next(image.Width);
     int y1 = random.Next(image.Height);
     int y2 = random.Next(image.Height);

     g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
    }

    Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
    g.DrawString(checkCode, font, brush, 2, 2);

    //画图片的前景噪音点
    for (int i = 0; i < 100; i++)
    {
     int x = random.Next(image.Width);
     int y = random.Next(image.Height);

     image.SetPixel(x, y, Color.FromArgb(random.Next()));
    }

    //画图片的边框线
    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    context.Response.ClearContent();
    context.Response.ContentType = "image/Gif";
    context.Response.BinaryWrite(ms.ToArray());
   }
   finally
   {
    g.Dispose();
    image.Dispose();
   }
  }
 }
}
 

然后在“ValidateCode.ashx”文件的第一行处输入上面这个类的调用代码

<%@ WebHandler language="C#" Class="CodeNamespace.ValidateCode" codebehind="ValidateCode.ashx.cs" %>

上面的代码需要注意的是:必须在Class项中输入类的完整名称,即包括名称空间及类名称。

最后保存并编译项目。

使用IE测试,输入这个.ashx的地址即可。

大家可以看出Response类有个OutputStream方法,可以向客户端输出二进制数据流,所以在我的项目中,使用这个方法,在一个.ashx中使用DundasChart控件就可以生成非常好的统计图,用它发送二进制数据,方便快捷,而且不需在web.config内输入任何配置代码。

.ashx文件有个缺点,他处理控件的回发事件非常麻烦,比如说如果用它来生成DataGrid的列表也不是不行,但是处理数据的回发,需要一些.aspx页的功能,只有自己手动处理这些功能。所以,一般使用.ashx,用来输出一些不需要回发处理的项目即可。

使用方法:

view plaincopy to clipboardprint?
<TR> 
                    <TD>Checkcode:</TD> 
                    <TD valign="bottom"> 
                        <asp:TextBox id="TBox_Checkcode" runat="server" MaxLength="6" columns="6"></asp:TextBox><FONT color="#ff0000"> *</FONT>    <IMG src="ValidateCode.ashx" mce_src="ValidateCode.ashx">      
                        <asp:LinkButton id="LinkButton1" runat="server" CausesValidation="False"><u>Click for another checkcode.</u></asp:LinkButton></TD> 
                </TR> 
<TR>
     <TD>Checkcode:</TD>
     <TD valign="bottom">
      <asp:TextBox id="TBox_Checkcode" runat="server" MaxLength="6" columns="6"></asp:TextBox><FONT color="#ff0000"> *</FONT>    <IMG src="ValidateCode.ashx" mce_src="ValidateCode.ashx">   
      <asp:LinkButton id="LinkButton1" runat="server" CausesValidation="False"><u>Click for another checkcode.</u></asp:LinkButton></TD>
    </TR>

view plaincopy to clipboardprint?
if(Session["CheckCode"] != null)  
            {  
                if (String.Compare(Session["CheckCode"].ToString(), this.TBox_Checkcode.Text.Trim(), true) != 0)  
                {  
                //错误信息  
                }  
else 
{  
//继续操作  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值