Wednesday, July 22, 2009

Application Life Cycle

Within ASP.NET, several processing steps must occur for an ASP.NET application to be initialized and process requests. Additionally, ASP.NET is only one piece of the Web server architecture that services requests made by browsers.

The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS).

IIS :
IIS (Internet Information Server) is a complete Web server that makes it possible to quickly and easily deploy powerful Web sites and applications. It is the default web server used with .NET.ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.

IIS maps the ASP.NET file extensions to ASPNET_ISAPI.DLL, an ISAPI extension provided with ASP.NET.

ASPNET_ISAPI.DLL: This dll is the ISAPI extension provided with ASP.NET to process the web page requests. IIS loads this dll and sends the page request to this dll. This dll loads the HTTPRuntime for further processing.

ASPNET_ISAPI.DLL forwards the request to the ASP.NET worker process (ASPNET_WP.EXE or W3P.EXE).

ASPNET_WP.EXE:
When a web page is requested, IIS looks for the application pool under which the current application is running and forwards the request to respective worker process.
Each worker process (ASPNET_WP.EXE) contains an Application Pool. Each Application Pool can contain any number of Applications. Application Pool is also called as AppDomain.

Application Domain :
When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provides access to information about the application such as the name of the folder where the application is stored.
The following diagram illustrates this relationship:
ASP.NET also compiles the top-level items in the application if required, including application code in the App_Code folder.

ISAPI loads HTTPRuntime and passes the request to it. Thus, HTTP Pipelining has begun.


HTTP Pipeline: HTTP Pipeline is the general-purpose framework for server-side HTTP programming that serves as the foundation for ASP.NET pages as well as Web Services. All the stages involved from creating HTTP Runtime to HTTP Handler is called HTTP Pipeline.
HTTP Runtime: Each AppDomain has its own instance of the HttpRuntime class—the entry point in the pipeline. The HttpRuntime object initializes a number of internal objects that will help carry the request out. The HttpRuntime creates the context for the request and fills it up with any HTTP information specific to the request. The context is represented by an instance of the HttpContext class. Another helper object that gets created at such an early stage of the HTTP runtime setup is the text writer—to contain the response text for the browser. The text writer is an instance of the HttpWriter class and is the object that actually buffers any text programmatically sent out by the code in the page. Once the HTTP runtime is initialized, it finds an application object to fulfill the request. The HttpRuntime object examines the request and figures out which application it was sent to (from the pipeline's perspective, a virtual directory is an application).
HTTP Context: This is created by HTTP Runtime. The HttpContext class contains objects that are specific to the current page request, such as the HttpRequest and HttpResponse objects. You can use this class to share information between pages. It can be accessed with Page.Context property in the code.
HTTP Request: Provides access to the current page request, including the request headers, cookies, client certificate, query string, and so on. You can use this class to read what the browser has sent. It can be accessed with Page.Request property in the code.HTTP Response: Provides access to the output stream for the current page. You can use this class to inject text into the page, to write cookies, and more. It can be accessed with Page.Response property in the code.
HTTP Application: An application object is an instance of the HttpApplication class—the class behind the global.asax file. HTTPRuntime uses HttpApplicationFactory to create the HTTPApplication object. The main task accomplished by the HTTP application manager is finding out the class that will actually handle the request. When the request is for an .aspx resource, the handler is a page handler—namely, an instance of a class that inherits from Page. The association between types of resources and types of handlers is stored in the configuration file of the application. More exactly, the default set of mappings is defined in the section of the machine.config file. However, the application can customize the list of its own HTTP handlers in the local web.config file. The line below illustrates the code that defines the HTTP handler for .aspx resources.
HttpApplicationFactory: Its main task consists of using the URL information to find a match between the virtual directory of the URL and a pooled HttpApplication object.
Note:
The first time an ASP.NET page or process is requested in an application, a new instance of HttpApplication is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.
When an instance of HttpApplication is created, any configured modules are also created. For instance, if the application is configured to do so, ASP.NET creates a SessionStateModule module. After all configured modules are created, the HttpApplication class's Init method is called.
The following diagram illustrates this relationship:

The following events are executed by the HttpApplication class while the request is processed. The events are of particular interest to developers who want to extend the HttpApplication class.
1. Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequest and Script Exploits Overview.
2. Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.
3. Raise the BeginRequest event.
4. Raise the AuthenticateRequest event.
5. Raise the PostAuthenticateRequest event.
6. Raise the AuthorizeRequest event.
7. Raise the PostAuthorizeRequest event.
8. Raise the ResolveRequestCache event.
9. Raise the PostResolveRequestCache event.
10. Based on the file name extension of the requested resource (mapped in the application's configuration file), select a class that implements IHttpHandler to process the request. If the request is for an object (page) derived from the Page class and the page needs to be compiled, ASP.NET compiles the page before creating an instance of it.
11. Raise the PostMapRequestHandler event.
12. Raise the AcquireRequestState event.
13. Raise the PostAcquireRequestState event.
14. Raise the PreRequestHandlerExecute event.
15. Call the ProcessRequest method (or the asynchronous version IHttpAsyncHandler..::.BeginProcessRequest) of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance handles the request.
16. Raise the PostRequestHandlerExecute event.
17. Raise the ReleaseRequestState event.
18. Raise the PostReleaseRequestState event.
19. Perform response filtering if the Filter property is defined.
20. Raise the UpdateRequestCache event.
21. Raise the PostUpdateRequestCache event.
22. Raise the EndRequest event.
23. Raise the PreSendRequestHeaders event.
24. Raise the PreSendRequestContent event.
HTTP Module: An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request. They also let you examine the outgoing response and modify it. ASP.NET uses modules to implement various application features, which includes forms authentication, caching, session state, and client script services. In each case, when those services are enabled, the module is called as part of a request and performs tasks that are outside the scope of any single page request. Modules can consume application events and can raise events that can be handled in the Global.asax file.

HTTPApplication creates HTTPHandler for the page request. This is the last stage of HTTPipelining. HTTPHandlers are responsible to process request and generate corresponding response messages.
HTTP Handler: An ASP.NET HTTP handler is the process that runs in response to a request that is made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page handler. We can write our own handler and handler factory if we want to handle the page request in a different manner.
Note: HTTP modules differ from HTTP handlers. An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.

HTTPHandler generates the response with the above events and sends back to the IIS which in turn sends the response to the client browser.


Once the request leaves the HTTPPipeline, page life cycle (page level events ) begins.