aps.net mvc中的Global.asax文件
一、Global.asax
- Global.asax文件会被动态编译成HttpApplication的实例,其Global.asax.cs文件中是一个MvcApplication类,继承自HttpApplication
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
二、Global.asax中与管道事件相关的处理程序
- ASP.NET使用命名约定Application_event(例如Application_BeginRequest)将Global.asax文件中的处理程序自动注册到HttpApplication中公布的应用程序事件中
三、Global.asax中的其他事件处理程序
处理程序或方法 | 描述 |
---|
Application_Start | 当请求ASP.NET应用程序中的第一个资源(例如页面)时调用。仅对创建的HttpApplication类的第一个实例可用。可以使用此方法执行启动任务,例如将数据加载到缓存中并初始化静态值 |
Init | HttpApplication类的public virtual方法,Global.asax中的MvcApplication继承自HttpApplication类;创建所有模块后,对HttpApplication类的每个实例调用一次 |
Dispose | HttpApplication类的public virtual方法;在销毁应用程序实例之前调用。可以使用此方法来手动释放任何非托管资源 |
Application_End | 在应用程序的整个生命周期中调用一次,然后再卸载应用程序 |
四、Global.asax中的其他约定
- 如果将自定义的IHttpModule添加到应用程序,则IHttpModule本身可以引发事件
- 需要在自定义的IHttpModule中的某个地方对事件进行invoke才能生效
- 可以在IHttpModule的init()方法中将事件的invoke过程注册到管道事件中
- 应用程序可以使用约定modulename_eventname来订阅Global.asax文件中的处理程序
- 例如,要处理由FormsAuthenticationModule对象引发的Authenticate事件,可以在Global.asax文件中创建一个名为FormsAuthentication_Authenticate的处理程序