httpmodule是如何工作的
當一個http請求到達httpmodule時,整個asp教程.net framework系統還並沒有對這個http請求做任何處理,也就是說此時對於http請求來講,httpmodule是一個http請求的“必經之路”,所以可以在這個http請求傳遞到真正的請求處理中心(httphandler)之前附加一些需要的資訊在這個http請求資訊之上,或者針對截獲的這個http請求資訊作一些額外的工作,或者在某些情況下乾脆終止滿足一些條件的http請求,從而可以起到一個filter過濾器的作用
using system;
using system.collections.generic;
using system.text;
using system.web;
namespace myhttpmodule
{
/// <summary>
/// 說明:用來實現自己的httpmodule類。
/// </summary>
public class myfirsthttpmodule : ihttpmodule
{
private void application_beginrequest(object sender, eventargs e)
{
httpapplication application = (httpapplication) sender;
httpcontext context = application.context;
httprequest request = application.request;
httpresponse response = application.response;
response.write("我來自自訂httpmodule中的beginrequest<br />");
}
private void application_endrequest(object sender, eventargs e)
{
httpapplication application = (httpapplication) sender;
httpcontext context = application.context;
httprequest request = application.request;
httpresponse response = application.response;
response.write("我來自自訂httpmodule中的endrequest<br />");
}
#region ihttpmodule 成員
public void dispose()
{
}
public void init(httpapplication application)
{
application.beginrequest += new eventhandler(application_beginrequest);
application.endrequest += new eventhandler(application_endrequest);
}
#endregion
}
}
httpmodule 的許可權管理
////下面是web.config 裡面的
<httpmodules>
<add name="scriptmodule" type="system.web.handlers.scriptmodule,
system.web.extensions, version=3.5.0.0, culture=neutral,
publickeytoken=31bf3856ad364e35"/>
<add name="mymodule" type="mymodule.mymodule"/>
<!--<add name="mymodule" type=""/>-->
</httpmodules>
///這樣每執行個頁面會調用這個方法。
.net代碼
using system.configuration;
using system.linq;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.htmlcontrols;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.xml.linq;
/// <summary>
///class1 的摘要說明
namespace mymodule
{
public class mymodule : ihttpmodule
{
/// <summary>
/// 初始化加入兩個事件到application 裡面去.
/// </summary>
/// <param name="application"></param>
public void init(httpapplication application)
{
application.beginrequest += (new
eventhandler(this.application_beginrequest));
application.endrequest += (new
eventhandler(this.application_endrequest));
}
///在這裡必須相當於是把response轉過來。在這雷根本直接用不了。不知道為啥。
///寫這個的作用是進行許可權判斷。
private void application_beginrequest(object source, eventargs e)
{
httpapplication application = (httpapplication)source;
httpresponse responseo教程k = application.context.response;
responseok.write("<h1>beginning of request</h1><hr>");
}
private void application_endrequest(object source, eventargs e)
{
httpapplication application = (httpapplication)source;
httpresponse responseok = application.context.response;
responseok.write("<h1>end of request</h1><hr>");
}
public void dispose() { }
}
}