c#中的IHttpHandler和IHttpModule

來源:互聯網
上載者:User

最近在交接,事情不多  所以就多逛逛園子,多研究一些以前沒研究過的東西

 

要說IHttpModule 以前我也用到過  比如 Url重寫 但那是別人寫的dll  一直覺得那重寫dll功能不太強  可是自己又不會

 

今天寫了一個簡單的樣本 原理大概是明白了  估計以前再碰到url重寫的問題  可以自己簡單寫個自己的dll來實現了

 

不多說了  貼代碼   雖然是新手代碼  也敢貼

 

IHttpModule 類

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;namespace Test{    class HttpModule : IHttpModule    {        #region IHttpModule 成員        public void Dispose()        {                    }        public void Init(HttpApplication context)        {            context.BeginRequest += new EventHandler(BeginRequest);            context.EndRequest += new EventHandler(EndRequest);                 }        void BeginRequest(object sender, EventArgs e)        {                     HttpApplication http = sender as HttpApplication;            if (http.Context.Request.Url.OriginalString.IndexOf("/index.cc") != -1)            {                                http.Context.Server.Transfer("default.aspx");            }            if (http.Context.Request.Form.Count > 3 || http.Context.Request.QueryString.Count > 0)            {                http.Context.Response.Write("哈哈!開始");            }        }        void EndRequest(object sender, EventArgs e)        {            HttpApplication http = sender as HttpApplication;                      http.Context.Response.Write("哈哈!結束");        }        #endregion    }}

 

web.config

 <httpModules>

 <add name="Test1" type="Test.HttpModel,Test"/>

  </httpModules>

 

IHttpModule 和IHttpHandler 兩者之間的區別在於

IHttpHandler 是完全替換頁面本身的 類似於java中的servlet

IHttpModule 則是在頁面之外進行操作 和頁面本身沒有任何關係

有點類似於設計模式中的適配器模式,把原來的頁麵包裝一下 

不知道我說的對不對

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.