这三个对象我们在开发Asp.net程序时经常会用到,似乎很熟悉,但有时候又不太确定。本文通过一个简单的例子来直观的比较一下这三个对象的使用。
HttpModule:Http模块,可以在页面处理前后、应用程序初始化、出错等时候加入自己的事件处理程序
HttpHandler:Http处理程序,处理页面请求
HttpHandlerFactory:用来创建Http处理程序,创建的同时可以附加自己的事件处理程序
例子很简单,就是在每个页面的头部加入一个版权声明。
一、HttpModule
这个对象我们经常用来进行统一的权限判断、日志等处理。
例子代码:

















web.config中配置:



在Init方法中可以注册很多application的事件,我们的例子就是在开始请求的时候加入自己的代码,将版权声明加到页面的头部
二、HttpHandler
这个对象经常用来加入特殊的后缀所对应的处理程序,比如可以限制.doc的文件只能给某个权限的人访问。
Asp.Net中的Page类就是一个IHttpHandler的实现
例子代码:












web.config中配置:




这个对象主要就是ProcessRequest方法,在这个方法中输出版权信息,但同时也有一个问题:原来的页面不会被处理,也就是说页面中只有版权声明了。那么所有的aspx页面都不能正常运行了
三、HttpHandlerFactory
这个对象也可以用来加入特殊的后缀所对应的处理程序,它的功能比HttpHandler要更加强大,在系统的web.config中就是通过注册HttpHandlerFactory来实现aspx页面的访问的:


HttpHandlerFactory是HttpHandler的工厂,通过它来生成不同的HttpHandler对象。
例子代码:































web.config中配置:



在例子中我们通过调用系统默认的PageHandlerFactory类进行常规处理,然后在处理过程中加入自己的代码,可以在Page对象上附加自己的事件处理程序。
附一个小的恶作剧:
我们可以开发好aspx页面,然后把web应用程序发布后把所有的aspx文件的后缀都改为spring,再在web.config中加入配置:








buildProviders是用来指定spring后缀的编译程序,我们把它设置成和aspx一致就可以了。如果在IIS中发布的话还需要在应用程序配置中加入spring的后缀映射。
然后我们就可以通过 http://../.../*.spring来访问我们的网站了
出处:https://www.cnblogs.com/firstyi/archive/2008/05/07/1187274.html