Global.asax与httpModule
-
共同点
两者创建的应用程序对象都能提供引用程序的全局访问点,两者都可以存储请求期间的全局状态和相应应用程序范围事件。 -
区别
Global只能伴随着应用程序,旨在管理特定应用程序的状态和事件。
HttpModule模块是完全独立的程序集,不必与特定的应用程序绑定,更适合实现多个应用程序通用的功能
Global.asax 实现HttpApplication的重写
通过gloabal中的全局事件可以方便的管理应用程序中的数据和事件。
创建Global.asax文件,文件中会有相应的事件处理程序
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context=HttpContext.Current;
context.Items["begin"] = DateTime.Now;
}
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpContext context=HttpContext.Current;
TimeSpan ts = DateTime.Now - (DateTime) context.Items["begin"];
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
- Application_Start
在应用程序初始化时运行,即第一个请求到达时,在整个应用程序生命周期开始时运行,只运行一次。可以加载和初始化数据。 - Application_End
在关闭应用程序时运行,可以清理需要特别释放的资源 - Application_Error
未处理的异常,可以在这里进行处理 - Application_BeginRequest
每次用户发起请求时都会被触发,注意:请求静态资源并不会触发。 - Session_Start
在每个用户最初请求应用程序时被触发 - Session_End
在会话被释放时触发。
HttpModule
也可以通过HTTP模块管理应用程序的数据和事件。
将httpModule融入到应用程序
- 编写实现IHttpModule接口的实现类
- 编写相关事件的处理程序
- 订阅事件
- 在web.config中配置模块
1-3代码:
namespace TimingModuleLIb
{
public class Timer:IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += OnBeginReq;
context.EndRequest += OnEndReq;
}
public void OnBeginReq(object sender,EventArgs e)
{
HttpContext context = HttpContext.Current;
context.Items["begin"] = DateTime.Now;
}
public void OnEndReq(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
TimeSpan ts = DateTime.Now - (DateTime)context.Items["begin"];
context.Response.Write(ts);
}
}
}
配置文件,IIS7
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="timingModule" type="TimingModuleLIb.Timer"/>
</modules>
</system.webServer>