The Global.asax file, sometimes called the ASP.NET application file, provides a way to respond to application or module level events in one central location. You can use this file to implement application security, as well as other tasks. Let's take a closer look at how you may use it in your application development efforts.
Overview
The Global.asax file is in the root application directory. While Visual Studio .NET automatically inserts it in all new ASP.NET projects, it's actually an optional file. It's okay to delete it--if you aren't using it. The .asax file extension signals that it's an application file rather than an ASP.NET file that uses aspx.
The Global.asax file is configured so that any direct HTTP request (via URL) is rejected automatically, so users cannot download or view its contents. The ASP.NET page framework recognizes automatically any changes that are made to the Global.asax file. The framework reboots the application, which includes closing all browser sessions, flushes all state information, and restarts the application domain.
Programming
The Global.asax file, which is derived from the HttpApplication class, maintains a pool of HttpApplication objects, and assigns them to applications as needed. The Global.asax file contains the following events:
The event list may seem daunting, but it can be useful in various circumstances.
Triggering
A key issue with taking advantage of the events is knowing the order in which they're triggered. The Application_Init and Application_Start events are fired once when the application is first started. Likewise, the Application_Disposed and Application_End are only fired once when the application terminates. In addition, the session-based events (Session_Start and Session_End) are only used when users enter and leave the site. The remaining events deal with application requests, and they're triggered in the following order:
Applying to security
A common use of some of these events is security. The following C# example demonstrates various Global.asax events with the Application_Authenticate event used to facilitate forms-based authentication via a cookie. In addition, the Application_Start event populates an application variable, while Session_Start populates a session variable. The Application_Error event displays a simple message stating an error has occurred.
protected void Application_Start(Object sender, EventArgs e) {
Application["Title"] = "Builder.com Sample";
}
protected void Session_Start(Object sender, EventArgs e) {
Session["startValue"] = 0;
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie) {
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try {
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
} catch(Exception ex) {
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket) {
// Cookie failed to decrypt.
return;
}
// When the ticket was created, the UserData property was assigned
// a pipe delimited string of role names.
string[2] roles
roles[0] = "One"
roles[1] = "Two"
// Create an Identity object
FormsIdentity id = new FormsIdentity( authTicket );
// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
protected void Application_Error(Object sender, EventArgs e) {
Response.Write("Error encountered.");
}
This example provides a peek at the usefulness of the events contained in the Global.asax file; it's important to realize that these events are related to the entire application. Consequently, any methods placed in it are available through the application's code, hence the Global name.
Here's the VB.NET equivalent of the previous code:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application("Title") = "Builder.com Sample"
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Session("startValue") = 0
End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As
EventArgs)
' Extract the forms authentication cookie
Dim cookieName As String
cookieName = FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie
authCookie = Context.Request.Cookies(cookieName)
If (authCookie Is Nothing) Then
' There is no authentication cookie.
Return
End If
Dim authTicket As FormsAuthenticationTicket
authTicket = Nothing
Try
authTicket = FormsAuthentication.Decrypt(authCookie.Value)
Catch ex As Exception
' Log exception details (omitted for simplicity)
Return
End Try
Dim roles(2) As String
roles(0) = "One"
roles(1) = "Two"
Dim id As FormsIdentity
id = New FormsIdentity(authTicket)
Dim principal As GenericPrincipal
principal = New GenericPrincipal(id, roles)
' Attach the new principal object to the current HttpContext object
Context.User = principal
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Response.Write("Error encountered.")
End Sub
A good resource
The Global.asax file is the central point for ASP.NET applications. It provides numerous events to handle various application-wide tasks such as user authentication, application start up, and dealing with user sessions. You should be familiar with this optional file to build robust ASP.NET-based applications.
我能在Global.asax文件中触发那些事件?
Application对象创建和结束时所触发的事件有
 Application_Start
 Application_End
Session对象创建和结束时所触发的事件有
• Session_Start
• Session_End
对程序有请求发生时触发的事件有 (按发生顺序排列)
• Application_BeginRequest
• Application_AuthenticateRequest
• Application_AuthorizeRequest
• Application_ResolveRequestCache
• Application_AcquireRequestState
• Application_PreRequestHandlerExecute
• Application_PostRequestHandlerExecute
• Application_ReleaseRequestState
• Application_UpdateRequestCache
• Application_EndRequest
当有程序有错误发生时触发的事件有
• Application_Error
• Application_Disposed