最近在交接,事情不多 所以就多逛逛園子,多研究一些以前沒研究過的東西
要說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 則是在頁面之外進行操作 和頁面本身沒有任何關係
有點類似於設計模式中的適配器模式,把原來的頁麵包裝一下
不知道我說的對不對