第三步:在Init事件中註冊PreRequestHandlerExecute事件,並實現事件處理方法
class AuthenticModule:IHttpModule{public void Dispose(){}public void Init(HttpApplication context){context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);}void context_PreRequestHandlerExecute(object sender, EventArgs e){HttpApplication ha = (HttpApplication)sender;string path = ha.Context.Request.Url.ToString();int n = path.ToLower().IndexOf("Login.aspx"); if (n == -1) //是否是登入頁面,不是登入頁面的話則進入{}{if (ha.Context.Session["user"] == null) //是否Session中有使用者名稱,若是空的話,轉向登入頁。{ha.Context.Response.Redirect("Login.aspx?source=" + path);}}}} |
第四步:在Login.aspx頁面的“登入”按鈕中加入下面代碼
protected void Button1_Click(object sender, EventArgs e){if(true)//判斷使用者名稱密碼是否正確{ if (Request.QueryString["source"] != null){string s = Request.QueryString["source"].ToLower().ToString(); //取出從哪個頁面轉來的Session["user"] = txtUID.Text;Response.Redirect(s); //轉到使用者想去的頁面}else{Response.Redirect("main.aspx");//預設轉向main.aspx}} } |
第五步:在Web.Conofig中註冊一下這個HttpModule模組
<httpModules> <add name="TestModule" type="ClassLibrary831.TestModule,ClassLibrary831"></add> </httpModules> |
3、多模組的操作
如果定義了多個HttpModule,在web.config檔案中引入自訂HttpModule的順序就決定了多個自訂HttpModule在處理一個HTTP請求的接管順序。
HttpHandler
HttpHandler是HTTP請求的處理中心,真正地對用戶端請求的伺服器頁面做出編譯和執行,並將處理過後的資訊附加在HTTP請求資訊流中再次返回到HttpModule中。
HttpHandler與HttpModule不同,一旦定義了自己的HttpHandler類,那麼它對系統的HttpHandler的關係將是“覆蓋”關係。
IHttpHandler介面聲明public interface IHttpHandler{bool IsReusable { get; }public void ProcessRequest(HttpContext context); //請求處理函數}樣本:把硬碟上的圖片以流的方式寫在頁面上class TestHandler : IHttpHandler{public void ProcessRequest(HttpContext context){FileStream fs = new FileStream(context.Server.MapPath("worm.jpg"), FileMode.Open);byte[] b = new byte[fs.Length];fs.Read(b, 0, (int)fs.Length);fs.Close();context.Response.OutputStream.Write(b, 0, b.Length);}public bool IsReusable{get{return true;}}} |