使用HttpModudel 首先注册IHttpModudel 接口
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public class ModuleDemo : IHttpModule { // 声明一个事件 public event EventHandler ExposedEvent; // Init方法仅用于给期望的事件注册方法 public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } // 处理BeginRequest 事件的实际代码 void context_BeginRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; context.Response.Write("<h3 style='color:#00f'>来自HttpModule的处理,请求到达</h3><hr>"); OnExposedEvent(new EventArgs()); } protected virtual void OnExposedEvent(EventArgs e) { if (ExposedEvent != null) // 如果Global中有注册 ExposedEvent(this, e); // 调用注册了的方法 } public void Dispose() { } }
然后在webconfig 注册该HttpModule 注册如下:
<httpModules> <add name="MyModule" type="ModuleDemo"/>
获取查看 HttpModule
ublic partial class RegisteredModules : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write(ShowModules()); } private string ShowModules() { HttpApplication app = Context.ApplicationInstance; //获取当前上下文的HttpApplication环境 HttpModuleCollection moduleCollection = app.Modules; //获取所有Module集合 // 获取所有的 Module 名称 string[] moduleNames = moduleCollection.AllKeys; System.Text.StringBuilder results = new System.Text.StringBuilder(); //遍历结果集 foreach (string name in moduleNames) { results.Append("<b style='color:#800800'>名称:" + name + "</b><br />"); // 获得Module名称 results.Append("类型:" + moduleCollection[name].ToString() + "<br />"); // 获得Module类型 } return results.ToString(); } }
本文代码引用: http://www.cnblogs.com/JimmyZhang/category/101697.html