Using ASP.net global.asax files

Source: Internet
Author: User
Tags decrypt execution http request httpcontext log client root directory visual studio
asp.net

Global.asax files, sometimes called asp.net application files, provide a way to respond to application-level or module-level events in a central location. You can use this file to implement security for your application and some other tasks. Let's take a look at how to use this file in the application development effort.
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. It doesn't matter if you delete it--of course, if you don't use it. The asax file name extension indicates that it is an application file, not a asp.net file that uses ASPX.


The Global.asax file is configured for any direct HTTP request (via URL) to be rejected automatically, so the user cannot download or view its contents. The ASP.net page framework automatically identifies any changes made to the Global.asax file. After the Global.asax is changed, the asp.net page framework restarts the application, including closing all browser sessions, removing all state information, and restarting the application domain.

Programming

The Global.asax file inherits from the HttpApplication class, which maintains a pool of HttpApplication objects and assigns objects from the object pool to the application when needed. The Global.asax file contains the following events:

· Application_init: This event is triggered when an application is instantiated or when it is invoked for the first time. It will be invoked for all HttpApplication object instances.

· Application_disposed: Triggers before the application is destroyed. This is the ideal place to clear previously used resources.

· Application_Error: The event is triggered when an unhandled exception is encountered in the application.

· Application_Start: The 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: The event is triggered when the last instance of the HttpApplication class is destroyed. It is only triggered once in the life cycle of an application.

· Application_BeginRequest: Triggered when an application request is received. For a request, it is the first event that is triggered, and the request is typically a page request (URL) entered by the user.

· Application_EndRequest: The last event requested for the application.

· Application_prerequesthandlerexecute: The event is triggered before the ASP.net page framework starts executing an event handler such as a page or Web service.

· Application_postrequesthandlerexecute: The event is triggered when an event handler is executed at the end of the ASP.net page frame.

· Applcation_presendrequestheaders: The event is triggered when the ASP.net page frame sends an HTTP header to the requesting client (browser).

· Application_presendcontent: This event is triggered when the ASP.net page frame sends content to the requesting client (browser).

· Application_acquirerequeststate: When the asp.net page frame gets the current state (session state) associated with the current request, the event is triggered.

· Application_releaserequeststate: This event is triggered when all event handlers are executed in the ASP.net page framework. This will cause all the state modules to hold their current state data.

· Application_resolverequestcache: The event is triggered when an authorization request is completed on the ASP.net page frame. It allows caching modules to service requests from the cache, bypassing the execution of event handlers.

· Application_updaterequestcache: When the asp.net page framework completes execution of an 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 point, the user's credentials will be validated.

· Application_authorizerequest: The event is triggered when the security module confirms that a user can access the resource.

· Session_Start: The 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 when they leave the application Web site.

This list of events may seem intimidating, but these events can be very useful in different contexts.


One of the key issues in using these events is to know the order in which they are triggered. The Application_init and Application_Start events are triggered once the application is first started. Similarly, application_disposed and Application_End events are triggered once when the application terminates. In addition, session-based events (Session_Start and session_end) are used only when the user enters and leaves the site. The remaining events handle application requests, which are triggered in the following order:

· Application_BeginRequest

· Application_AuthenticateRequest

· Application_authorizerequest

· Application_resolverequestcache

· Application_acquirerequeststate

· Application_prerequesthandlerexecute

· Application_presendrequestheaders

· Application_presendrequestcontent

· << Execute Code >>

· Application_postrequesthandlerexecute

· Application_releaserequeststate

· Application_updaterequestcache

· Application_EndRequest

These events are often used for security purposes. The following example of C # illustrates a different Global.asax event, which uses the Application_authenticate event to complete the form based authentication of the cookie. In addition, the Application_Start event populates an application variable, while session_start fills a session variable. The Application_Error event displays a simple message indicating the error that 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 Cookies
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 is created, the UserData property is 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'll 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 the events in some global.asax files, and it is important to realize that these events are related to the entire application. In this way, all the methods put in it are provided through the application's code, which is why its name is global.

Here is the previous example of 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 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

Resources

The Global.asax file is the central point of the ASP.net application. It provides countless events to handle different application-level tasks, such as user authentication, application startup, and processing of user sessions. You should be familiar with this optional file, so you can build a robust asp.net application.



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.