现在的位置: 首页 > 综合 > 正文

Asp.net 中HttpHandler,HttpModule,IHttpHandlerFactory的原理与应用(二)(转)

2012年01月14日 ⁄ 综合 ⁄ 共 2103字 ⁄ 字号 评论关闭

在Asp.net 中HttpHandler,HttpModule,IHttpHandlerFactory的原理与应用(一)中提到,HttpModule会在页面处理前和后执行,而HttpHandler才是真正的页面处理。查看C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config,你就会发现里面有很多关于Httpmodule和httphandler的定义。比方说,httpmodule中定义了在页面处理前(后)要进行权限,角色,session等等的检查和控制,而httphandler则定义了,对于不同的页面请求(根据后缀名判断),执行对应的处理程序.如.aspx, .asmx,.skin等等都有对应的type定义处理程序.
既然httphandler定义了特定页面请求的处理程序。那么如果我们自定义httphandler,对于我们定义的页面,如果client有所请求,将只能按照我们定义的处理程序来处理。(也就是说,我们自定义的处理代替了原来base处理)。
他的应用也是显见的:比如可以进行资源的权限控制。如果那些页面需要一定的权限才能访问(比如处在某个IP段),不然就输出我们自定义的警告信息; 当然如果client通过url直接访问站内资源,也可以用httphandler控制(如.doc文件)。
   下面是msdn的一个范例:
1.建立处理类

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.IO;

/**//// <summary>
/// HandlerTest 的摘要描述
/// </summary>
///
namespace HanlderAndModule
...{
    
public class ImageHandler : IHttpHandler
    
...{
        
//
        public void ProcessRequest(HttpContext context)
        
...{
             context.Response.Write(
"<H1>This is an HttpHandler Test.</H1>");
             context.Response.Write(
"<p>Your Browser:</p>");
             context.Response.Write(
"Type: " + context.Request.Browser.Type + "<br>");
             context.Response.Write(
"Version: " + context.Request.Browser.Version);
         }

        
// Override the IsReusable property.
        public bool IsReusable
        
...{
            
get ...{ return true; }
         }

     }

}

可以看到,上面自定义实际上实现了IHttpHandler的一个方法:ProcessRequest,一个属性:IsReusable.实际上请求处理都是在ProcessRequest中处理的.
2.按照一z中所说建立DLL文件,添加到Bin目录下
3.配置web.config

<httpHandlers>
      
<add verb="*" path="Default2.aspx" type="HanlderAndModule.ImageHandler,HanlderAndModule"/>
      
<add verb="*" path="*.Doc" type="HanlderAndModule.ImageHandler,HanlderAndModule"/>
</httpHandlers>

这里定义了,如果client请求Default2.aspx页面时,或者直接请求.Doc文件时,就调用这个自定义的处理程序。
其中的含义:verb指client的请求类别;path指出对什么页面调用处理程序;type指出处理程序路径,定义方法和httmodule一样。
4.建立几个doc文档,建立几个页面,运行发现:当访问Default.aspx, 和XXX/a.doc时,不管你在页面中做过什么,页面只会出现:

This is an HttpHandler Test.
Your Browser:

Type: IE6
Version: 6.0

而访问其他资源,则正常显示.

抱歉!评论已关闭.