描述三個C#對象的使用
本文介紹HttpModule,HttpHandler,HttpHandlerFactory簡單使用,這三個C#對象的使用我們在開發ASP.NET程序時經常會用到,似乎很熟悉,但有時候又不太確定。本文通過一個簡單的例子來直觀的比較一下這三個C#對象的使用。
◆HttpModule:Http模塊,可以在頁面處理前后、應用程序初始化、出錯等時候加入自己的事件處理程序
◆HttpHandler:Http處理程序,處理頁面請求
◆HttpHandlerFactory:用來創建Http處理程序,創建的同時可以附加自己的事件處理程序
例子很簡單,就是在每個頁面的頭部加入一個版權聲明。
一、HttpModule
這個對象我們經常用來進行統一的權限判斷、日志等處理。
例子代碼:
- publicclassMyModule:IHttpModule
- {
- publicvoidInit(HttpApplicationapplication)
- {
- application.BeginRequest+=newEventHandler(application_BeginRequest);
- }
- voidapplication_BeginRequest(objectsender,EventArgse)
- {
- ((HttpApplication)sender).Response.Write("Copyright@Gspring<br/>");
- }
- publicvoidDispose()
- {
- }
- }
在Init方法中可以注冊很多application的事件,我們的例子就是在開始請求的時候加入自己的代碼,將版權聲明加到頁面的頭部
二、HttpHandler
這個對象經常用來加入特殊的后綴所對應的處理程序,比如可以限制.doc的文件只能給某個權限的人訪問。
Asp.Net中的Page類就是一個IHttpHandler的實現
例子代碼:
- publicclassMyHandler:IHttpHandler
- {
- publicvoidProcessRequest(HttpContextctx)
- {
- ctx.Response.Write("Copyright@Gspring<br/>");
- }
- publicboolIsReusable
- {
- get{returntrue;}
- }
- }
這個對象主要就是ProcessRequest方法,在這個方法中輸出版權信息,但同時也有一個問題:原來的頁面不會被處理,也就是說頁面中只有版權聲明了。那么所有的aspx頁面都不能正常運行了
三、HttpHandlerFactory
這個對象也可以用來加入特殊的后綴所對應的處理程序,它的功能比HttpHandler要更加強大,在系統的web.config中就是通過注冊HttpHandlerFactory來實現aspx頁面的訪問的。
HttpHandlerFactory是HttpHandler的工廠,通過它來生成不同的HttpHandler對象。
- publicclassMyHandlerFactory:IHttpHandlerFactory
- {
- publicIHttpHandlerGetHandler(HttpContextcontext,stringrequestType,
stringurl,stringpathTranslated)- {
- PageHandlerFactoryfactory=(PageHandlerFactory)Activator.
CreateInstance(typeof(PageHandlerFactory),true);- IHttpHandlerhandler=factory.GetHandler
(context,requestType,url,pathTranslated);- //執行一些其它操作
- Execute(handler);
- returnhandler;
- }
- privatevoidExecute(IHttpHandlerhandler)
- {
- if(handlerisPage)
- {
- //可以直接對Page對象進行操作
- ((Page)handler).PreLoad+=newEventHandler(MyHandlerFactory_PreLoad);
- }
- }
- voidMyHandlerFactory_PreLoad(objectsender,EventArgse)
- {
- ((Page)sender).Response.Write("Copyright@Gspring<br/>");
- }
- publicvoidReleaseHandler(IHttpHandlerhandler)
- {
- }
- }
以上介紹三個C#對象的使用。
【編輯推薦】