Use the ASP. NET global. asax file-Basics

Source: Internet
Author: User
Use the ASP. NET global. asax File
 
The global. asax file is sometimes called an ASP. NET application. Program File, provides a way 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 starts to execute 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: When the ASP. NET page framework executes the event processing program, this event is triggered, so that the cache module stores 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 the resource.

· 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

· <ExecutionCode>

· 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.

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.