Use the Global. asax file in ASP. NET

Source: Internet
Author: User

The Global. asax file, sometimes called an ASP. NET application file, provides a method to respond to application-level or module-level events at a central location. You can use this file to implement application security and other tasks. The following describes how to use this file in application development.

Overview

Global. asax is located in the application root directory. Although Visual Studio. NET automatically inserts this file into all ASP. NET projects, it is actually an optional file. There is no problem with deleting it-of course you are not using it .. The asax file extension indicates that it is an application file, rather than an ASP. NET file that uses aspx.

The Global. asax file is configured as any direct HTTP Request (via URL) and is automatically rejected. Therefore, users cannot download or view its content. The ASP. NET page framework can automatically identify any changes made to the Global. asax file. After Global. asax is changed, the ASP. NET page framework restarts the application, including closing all browser sessions, removing all status information, and restarting the application domain.

Programming

The Global. asax file inherits from the HttpApplication class. It maintains an HttpApplication Object pool and assigns the objects in the pool to the application as needed. The Global. asax file contains the following events:

· Application _ Init: this event is triggered when an Application is instantiated or called for the first time. All HttpApplication object instances are called.

· Application _ Disposed: triggered before the Application is destroyed. This is an ideal location for clearing previously used resources.

· Application _ Error: this event is triggered when an unhandled exception is encountered in the Application.

· Application _ Start: this event is triggered when the first instance of the HttpApplication class is created. It allows you to create objects that can be accessed by all HttpApplication instances.

· Application _ End: this event is triggered when the last instance of the HttpApplication class is destroyed. It is triggered only once during the lifecycle of an application.

· Application _ BeginRequest: triggered when an Application request is received. A request is the first trigger event. A request is generally a page request (URL) entered by the user ).

· Application _ EndRequest: the last event requested by the Application.

· Application _ PreRequestHandlerExecute: this event is triggered before the ASP. NET page framework executes Event Handlers such as pages or Web services.

· Application _ PostRequestHandlerExecute: this event is triggered when the ASP. NET page framework finishes executing an event handler.

· Applcation _ PreSendRequestHeaders: this event is triggered when the ASP. NET page framework sends an HTTP header to the requesting client (browser.

· Application _ PreSendContent: this event is triggered when the ASP. NET page framework sends content to the requesting client (browser.

· Application _ AcquireRequestState: this event is triggered when the ASP. NET page framework obtains the current state (Session state) related to the current request.

· Application _ ReleaseRequestState: this event is triggered when all event handlers are executed on the ASP. NET page framework. This causes all status modules to save their current status data.

· Application _ ResolveRequestCache: this event is triggered when the ASP. NET page framework completes an authorization request. It allows the cache module to provide services for requests from the cache, bypassing the execution of event handlers.

· Application _ UpdateRequestCache: In ASP. when the NET page framework completes the execution of the event handler, the event is triggered, so that the cache module stores the response data for use in response to subsequent requests.

· Application _ AuthenticateRequest: this event is triggered when the security module establishes a valid identity for the current user. At this time, the user's creden。 will be verified.

· Application _ AuthorizeRequest: this event is triggered when the security module confirms that a user can access resources.

· Session _ Start: this event is triggered when a new user accesses the Application Web site.

· Session _ End: this event is triggered when a user's Session times out, ends, or leaves the application Web site.

This event list seems to be scary, but these events may be very useful in different environments.

A key issue with using these events is to know the order in which they are triggered. The Application_Init and Application_Start events are triggered once when the application is started for the first time. Similarly, Application_Disposed and Application_End events are triggered once upon application termination. In addition, session-based events (Session_Start and Session_End) are only used when users enter and exit the site. Other events process application requests. These events are triggered in the following order:

· Application _ BeginRequest

· Application _ AuthenticateRequest

· Application _ AuthorizeRequest

· Application _ ResolveRequestCache

· Application _ AcquireRequestState

· Application _ PreRequestHandlerExecute

· Application _ PreSendRequestHeaders

· Application _ PreSendRequestContent

· <Execution Code>

· Application _ PostRequestHandlerExecute

· Application _ ReleaseRequestState

· Application _ UpdateRequestCache

· Application _ EndRequest

These events are often used for security. The following C # example demonstrates different Global. asax events. This example uses the Application_Authenticate event to complete form-based authentication through cookies. In addition, the Application_Start event fills in an application variable, while Session_Start fills in a session variable. The Application_Error event displays a simple message to indicate an error.

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 simply uses some events in the Global. asax file. It is important to realize that these events are related to the entire application. In this way, all methods put in it will be provided through the application code, which is why its name is Global.

The preceding example shows the corresponding VB. NET 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

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

Resources

The Global. asax file is the central point of ASP. NET applications. It provides numerous events to process different application-level tasks, such as user authentication, application startup, and user session processing. You should be familiar with this optional file so that you can build robust ASP. NET applications.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.