Use the global.asax file in ASP.NET

xiaoxiao2021-03-05  23

Global.asax files, sometimes called ASP.NET application files, providing a method of responding to application-level or module-level events in a central location. You can use this file to implement application security and other tasks. Let us take a detailed look at how to use this file in application development work.

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. Deleting it doesn't have problems - of course, if you don't use it. .asax file extension points out that it is an application file instead of an ASP.NET file using ASPX.

The Global.asax file is configured to be automatically rejected (by URL) Direct HTTP requests, so users cannot download or view their content. The ASP.NET page framework automatically recognizes any changes to the Global.asax file. After Global.asax is changed, the ASP.NET page framework will restart the application, including all browser sessions, remove all status information, and restart the application domain.

Program

The global.asax file inherits from the HTTPApplication class, which maintains an HTTPApplication object pool and assigns objects in the object pool to the application when needed. The global.asax file contains the following events:

Application_init: This event is triggered when the application is instantiated or first called. It will be called for all HTTPApplication object instances.

Application_Disposed: Triggered before the application was destroyed. This is the ideal location for clearing the previous resources.

· Application_ERROR: This event is triggered when an unprocessed exception is encountered in the application.

Application_Start: When the first instance of the HTTPApplication class is created, the event is triggered. It allows you to create objects that can be accessed by all HTTPApplication instances.

Application_end: When the last instance of the HTTPApplication class is destroyed, the event is triggered. It is only triggered once in the life cycle of an application.

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

Application_endRequest: The last event for the application request.

· Application_PreRequestHandleRexecute: This event is triggered before the ASP.NET page framework begins with an event handler such as a page or a web service.

· Application_PostRequestHandleRexecute: This event is triggered when an event handler is executed in the ASP.NET page frame.

AppLCATION_PresendRequestHeaders: This event is triggered when the ASP.NET page frame sends an HTTP header to the requesting customer (browser).

· Application_PresendContent: This event is triggered when the ASP.NET page frame is sent to the request client (browser).

Application_AcquireRequestState: When the ASP.NET page framework is obtained, the event is triggered when the current state (SESSION state) is related to the current request. Application_ReleaseRequestState: This event is triggered when all event handles are executed on the ASP.NET page framework. This will result in all state modules to save their current status data.

· Application_ResolveRequestCache: This event is triggered when an ASP.NET page framework is completed. It allows the cache module to provide services to the request from the cache to bypass the execution of the event handler.

Application_UpdateRequestCache: When the ASP.NET page frame completes the execution of the event handler, the event is triggered so that the cache module is stored responded to the response to the subsequent request.

Application_AuthenTicateRequest: This event is triggered when the security module establishes a valid identity of the current user. At this time, the user's credentials will be verified.

Application_Authorzerequest: This event is triggered after a security module confirms that one 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 timeout, end or they leave the application web site.

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

A key issue using these events is to know the order they are triggered. Application_init and Application_Start events are triggered once when the application starts. 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 rest of the event handle the application request, and these events are triggered.

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 in security. The example below demonstrates different Global.asax events that use the Application_Authenticate event to complete form-based authentication based on cookie. In addition, the Application_Start event populates an application variable, while session_start fills a session variable. Application_Error event Displays a simple message to illustrate an error 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;} //1 Tickety Was Assigned // a pipe delimited string of role names. String [2] Roles Roles [0] = "one" roles [1] = "Two" // create an identity objectict formsidentity id = new formsidentity (autht icket); // 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 only simply uses 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 placed will be provided through the application's code, which is why it is Global.

Here is the previous example 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 Formentity (Authticket) Dim Principal AS GenericPrincipal Principal = New GenericPrincipal (ID, ROLES) 'Attach THE N ew 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 numerous events to handle different application-level tasks, such as user authentication, application launch, and handle user sessions. You should be familiar with this optional file so you can build a strong ASP.NET application.

转载请注明原文地址:https://www.9cbs.com/read-38044.html

New Post(0)