Overview of ASP. _httpmodule and Application life cycle _2

Source: Internet
Author: User
Tags httpcontext

I. List of HttpModule events

BeginRequest

Indicates that the request processing begins.

AuthenticateRequest

Postauthenticaterequest

Encapsulates the request authentication process.

AuthorizeRequest

Postauthorizerequest

Encapsulates the request authorization process.

Resolverequestcache

Postresolverequestcache

Encapsulates the process of checking whether a previously cached output page can be used to process requests.

Postmaprequesthandler

Indicates that an HTTP handler was found to handle the request.

AcquireRequestState

Postacquirerequeststate

Encapsulates the retrieval of the requested session state.

PostRequestHandlerExecute

Indicates that the HTTP handler used to process the request has been executed.

ReleaseRequestState

Postreleaserequeststate

Encapsulates the publication of a request session state.

Updaterequestcache

Postupdaterequestcache

The encapsulation checks whether the output of the requested resource should be cached for future reuse.

EndRequest

Indicates the end of the request processing.

Ii. HttpModule Event Flow

Iii. Creating a custom HTTP module

Let's look at the IHttpModule interface first, which includes the following two methods:

public void Init (HttpApplication context);p ublic void Dispose ();

Init (): This method accepts a HttpApplication object,HttpApplication represents the current application, and we need to register it within this method The event that the HttpApplication object exposes to the client. Visible, this method is only used to register the event, and the actual event handler, we need to write another method.

The whole process is well understood:

1.0 when the site first resource is accessed, ASP. NET creates an instance of the HttpApplication class that represents the site application and creates all the module instances that are registered in Web. config.

2.0 the module's init () method is called when the module instance is created.

3.0 within the init () method, register the event exposed by the HttpApplication that you want to respond to. (The actual method needs to be written separately, simply by simply registering the method).

4.0 HttpApplication triggers various events in its application cycle.

5.0 invokes the method that the module has registered in its init () method when the event is triggered.

Dispose (): It can do some cleanup work before garbage collection.

In summary: The implementation of a ihttpmodule template is generally the case:

public class definemodule:ihttpmodule{public    void Init (HttpApplication context) {       //register HttpApplication application The BeginRequest event       //can also be any other HttpApplication exposed event       context. BeginRequest + = new EventHandler (context_beginrequest);    }    void Context_beginrequest (object sender, EventArgs e) {       HttpApplication application = (HttpApplication) sender;       HttpContext context = Application. Context;       Do some practical work, HttpContext objects are obtained, the rest of the basic can be free to play the    } public    void Dispose () {    }}

Iv. registering a custom HTTP module (webconfig)

1.0 IIS6 and IIS7 Classic models

<configuration>  <system.web>    "  HelloWorldModule" type="helloworldmodule"/>     

Note:type= "namespace + category name , component name"

2.0 Registration module for IIS7.0 running in Integrated mode

<configuration>     <system.webServer>                  <modules>                              <add name="  HelloWorldModule "type="helloworldmodule"/>              </modules>         </system.webServer></configuration> Note: type=" namespace + category name, component name "

V.HttpModule and Global.asax files (new Global application Class)

1.0 Global.asax file (also known as ASP. NET application file) is an optional file that contains the response ASP. NET or HTTP modules, the code for the application-level and session-level events raised by the the Global.asax file resides in ASP. NET application in the root directory. The runtime parses the Global.asax file and compiles it into a dynamically generated . NET Framework class that derives from the HttpApplication base class. Configure ASP. NET to automatically deny any direct URL requests to the Global.asax file , and external users cannot download or view the code in it. The Global.asax file is optional and is created only when you want to handle an application event or session event.

implementation of the global file:

For example, IIS now receives a request to access an ASP. IIS will map this request to aspnet_isapi.dll.WhenAspnet_isapi.dll when this request is received, a newThe process of aspnet_wp.exe (windows Server 2003 is the w3wp.exe process, which passes the request to a specified appdomain is created, the information in some configuration files is loaded (the loading order is from machine.config files to web.config files), and when this information is loaded, appdomain will go to get a HttpApplication instance, then global class will be compiled loaded, then appdomain will do some related processing to create page class, and the last page renders to the client browser. But here's a little bit of a problem to note, when the configuration file is loaded, it does not mean that appdomain will load all the information in the configuration file, but just load some needed information. Some configuration information is loaded appdomain when needed. For example, we have configured many httpmodule in the web.config file, only if each appdomain to load and process this information. So web.config files and global no sequential execution, just depending on when the specific information is loaded and processed.

Meaning of the method in Global.asax.cs:

Application_init: Executed at each HttpApplication instance initialization.

Application_disposed: Executed before each HttpApplication instance is destroyed.

Application_Error: All errors that are not handled will result in the execution of this method.

Application_Start: Executes when the program initializes. Executes once in the life cycle of a Web application, where there is only a few common information, such as HttpApplicationState.
Application_End: When the application finishes, it executes after the last HttpApplication is destroyed. The corresponding Application_Start is executed only once throughout the life cycle.
Session_Start: Executed at the beginning of the session.
Session_End: Executes when the session ends or expires.
Application_beginrequest:beginrequest is the first event triggered when a request is received, and this method executes first.
Application_AuthenticateRequest: Executes when the security module has established the identity of the current user.
Application_authorizerequest: Executed when the security module has verified the authorization of the current user.
Application_resolverequestcache: Occurs when an ASP. NET finishes authorization event to enable the cache module to service the request from the cache, skipping the execution of the handler (page or WebService). This can improve the performance of the site, which can also be used to determine whether the body is obtained from the cache.
Application_acquirerequeststate: Executes when ASP. NET gets the current state associated with the current request, such as a session.
Application_prerequesthandlerexecute: When ASP. NET will be executed before the request is sent to the Handler object (page or WebService), the session can be used.
Application_postrequesthandlerexecute: Executes when the handler object finishes working.
Application_releaserequeststate: Executes after all request handlers have been executed by ASP. The ReleaseRequestState event causes the current state data to be saved.
Application_updaterequestcache: Executes when the response cache is updated for subsequent requests after ASP. NET finishes executing the handler.
Application_EndRequest: Ibid., EndRequest is the last event triggered when responding to a request, and this method is naturally the last one to execute.
Application_presendrequestheaders: Executes before sending HTTP headers to the client.
Application_presendrequestcontent: Executes before sending the HTTP body to the client.

Vi. Choice of Global and HttpModule

Many of the features of HttpModule can be implemented in the application's Global.asax file , which enables you to respond to application events. HttpModule has the following advantages over Global.asax files:HttpModule can be encapsulated and can be used in many different applications once created. If you add them to the global Assembly Cache (GAC) and register them in the machine.config file, you can reuse them across applications.

One advantage of using the Global.asax file is that you can put your code in other registered module events, such as the Session_Start and session_end methods. In addition , the Global.asax file allows the instantiation of the global object to be used throughout the application.

Use HttpModule when you need to create code that relies on application events and you want to reuse HttpModule in other applications , or if you do not want to put complex code in a Global.asax file . When you need to create code that relies on application events, but you do not need to reuse it across applications, or if you need to subscribe to events that are not available for HttpModule, such as session_start, you should place your code in the Global.asax file.

Note: Which of the processes in HttpModule are not available

The session cannot be used until the AcquireRequestState event because the session state has not yet been loaded .

The cache cannot be used until the Maphandlerexecutionstep event because the handler state is not loaded.

Eight, remove unnecessary httpmodule can optimize performance

In the. NET Framework2The built-in HttpModule configured in the. 0 version of the Web. config file optimizes performance by removing unwanted httpmodule as needed. For example, the following httpmodule are removed from the moving products according to the actual situation:<remove name="windowsauthentication"/>set the identity of the ASP. NET application user with Windows authentication enabled. <remove name="passportauthentication"/>provides a wrapper around the Passport authentication service. <remove name="rolemanager"/>manages RolePrincipal instances of the current user. <remove name="fileauthorization"/>Verify that the remote user has permission to access the requested file. <remove name="anonymousidentification"/>manages anonymous identifiers for ASP. <remove name=" Profile"/>manages the creation of user profiles and profile events. 

Overview of ASP. _httpmodule and Application life cycle _2

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.