httpHandlers和httpModules介面介紹 (3)

來源:互聯網
上載者:User

第三步:在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;}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.