Use the global. asax document in ASP. NET

Source: Internet
Author: User
The global. asax documentation, sometimes called the asp.net application documentation, provides a method to respond to application-level or module-level events in a central location. You can use this document to implement application security together with other tasks. The following describes how to use this document in application development.
Overview
Global. asax is located in the application root directory. Although visual studio. net automatically inserts this document into any asp.net project, it is actually an optional document. There is no problem with deleting him. Of course, you didn't use him .. The asax document extension specifies that it is an application document, rather than an asp.net document that uses aspx.
The global. asax document is configured to automatically reject any direct http Request (via url), so users cannot download or view its content. The asp.net page framework can automatically identify any changes made to the global. asax document. After global. asax is changed, the asp.net page framework restarts the application, including closing any browser session, removing any status information, and restarting the application domain.
Programming
The global. asax document 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 document contains the following events:
· Application _ init: this event is triggered when an application is instantiated or called for the first time. Any httpapplication object instance will be 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 any httpapplication instance.
· Application _ end: this event is triggered when the last instance of the httpapplication class is destroyed. An application is triggered only once in its lifecycle.
· 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 processing program.
· 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: When the asp.net page framework obtains the current state (session state) related to the current request, this event is triggered.
· Application _ releaserequeststate: this event is triggered when any event handler is executed on the Asp.net page framework. This will cause any status module 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 the event processing program.
· Application _ updaterequestcache: When the Asp.net page framework completes the execution of 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 list of events seems to be quite scary, but these events may be 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 is filled with an application variable, while session_start is filled with 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 uses some events in the global. asax documentation. It is important to realize that these events are related to the entire application. In this way, any method put in it will be provided through the application code, which is why its name is global.
Here is the corresponding vb.net code in the previous example:
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 document is the central point of the asp.net application. He 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 document so that you can build a robust asp.net application.

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.