Asp.net page life cycle
Introduction Many of us know that IIS is a web server and we use it in our .Net application since we need a web server to run a web application. But I wonder as many of us don't know the internal architecture of IIS. This article is written for beginners to know the architecture of IIS. How the simple web page execution happens? As all of us know a request comes from Client (Browser) and sends to Server (we call it as Web server) in turn server process the request and sends response back to the client in according to the client request. But internally in the web server there is quite interesting process that happens. To get aware of that process we should first of all know about the architecture of the IIS It mainly consists of 3 Parts/Files 1. Inetinfo.exec 2. ISAPI Filer (Container for Internet Server Application Interface dlls), 3. Worker Process (aspnet_wp.exe) When ever a request comes from the client: Inetinfo.exe is the ASP.Net request handler that handles the requests from the client .If it's for static resources like HTML files or image files inetinfo.exe process the request and sent to client. If the request is with extension aspx/asp, inetinfo.exe processes the request to API filter. ISAPI filter will have several runtime modules called as ISAPI extensions. To process the request ISAPI filter takes the help of these runtime modules. The runtime module loaded for ASP page is asp.dll. And for ASP.NET page it's ASPNET_ISAPI.dll. From here the request is processed to the "worker process". Worker Process will have several application domains. Application Domain The purpose of the application domain is in order to isolate one application from another. When ever we create a new application, application domains are created automatically by the CLRHost. Worker process will create a block of memory related to particular application. Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. Application domains are normally created by runtime hosts. Runtime host is responsible for bootstrapping the common language runtime before an application is run. Worker process sends the request to HTTPPIPE line.(HTTP Pipeline is nonetheless collection of .net framework classes). HTTP Pipeline compiles the request into a
library and makes a call to HTTP runtime and runtime creates an instance of page class public class File : System.Web.UI.Page {} ASP.Net web page is a class derived from page class, this page class resides in system.web.dll After creating instance pf page class HTTP Runtime immediately invokes process request method of page class Page Req = new Page(); Req.ProcessRequest(); Process Request Method does following things: 1. 2. 3. 4. 5.
Intialize the memory Load the view state Page execution and post back events Rendering HTML content Releasing the memory
Process Request Method executes set of events for page class .These are called as Page life cycle events. Page Life Cycle Events • •
• • • • • • •
Page_Init The server controls are loaded and initialized from the Web form's view state. This is the first step in a Web form's life cycle. Page_Load The server controls are loaded in the page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page. Page_PreRender The application is about to render the page object. Page_Unload The page is unloaded from memory. Page_Disposed The page object is released from memory. This is the last event in the life of a page object. Page_Error An unhandled exception occurs. Page_AbortTransaction A transaction is aborted. Page_CommitTransaction A transaction is accepted. Page_DataBinding A server control on the page binds to a data source.
•
Process Request Method finally renders HTML Page
Dependencies: When the request comes to ASP.net worker process, it will be forwarded to HTTP Application factory. This "Application Factory" will maintain address of the application domains which are currently executing under worker process. If the required virtual directory application domain is unavailable it will create a new application domain. If the application domain is already existing, the request will be forwarded to corresponding AppDomain. Application Domain maintains page handler factory class. This will contain all libraries addresses corresponding to webpage. If the requested webpage library is available the instance of the page class is created, if the library is unavailable the request will be forwarded to HTTP pipeline. Note: In ASP 2.0 we don't need to install IIS in your system. It comes with built-in ASP server. Is this clear and enough or confusing!!!
In this article, we will see the stages of execution of the ASP.NET Page. Each request for an .aspx page that hits IIS is handed over to HTTP Pipeline. HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content. The start point of HTTP Pipeline is the HttpRuntime class. The ASP.NET infrastructure creates each instance of this class per AppDomain hosted within the worker process. HttpRuntime class picks up an HttpApplication object from an internal pool and sets it to work on the request. It finds out what class has to handle the request. The association between the resources and handlers are stored in the configurable file of the application. In web.config and also in machine.config you will find these lines in
section. If you run through the following program, it will be much easier to follow This extension can be associated with HandlerClass or HandlerFactory class. HttpApplication object gets the page object that implements the IHttpHandler Interface. The process of generating the output to the browser is started when the object calls ProcessRequest method. Page Life Cycle Once the HTTP page handler class is fully identified, the ASP.NET runtime calls the handler's ProcessRequest to start the process. This implementation begins by
calling the method FrameworkInitialize(), which builds the control trees for the page. This is a protected and virtual member of TemplateControl class, class from which page itself derives. Next the processRequest() makes page transits various phases: initialization, loading of viewstate and postback data, loading of page's user code and execution postback server-side events. Then page enters in render mode, the viewstate is updated and HTML generated is sent to the output console. Finally page is unloaded and request is considered completely served. Stages and corresponding events in the life cycle of the ASP.NET page cycle: Stage Page Initialization View State Loading Postback data processing Page Loading PostBack Change Notification PostBack Event Handling Page Pre Rendering Phase View State Saving Page Rendering Page Unloading
Events/Method Page_Init LoadViewState LoadPostData Page_Load RaisePostDataChangedEvent RaisePostBackEvent Page_PreRender SaveViewState Page_Render Page_UnLoad
Some of the events listed above are not visible at the page level. It will be visible if you happen to write server controls and write a class that is derived from page. Page Execution Stages The first stage in the page life cycle is initialization. This is fired after the page's control tree has been successfully created. All the controls that are statically declared in the .aspx file will be initialized with the default values. Controls can use this event to initialize some of the settings that can be used throughout the lifetime of the incoming web request. Viewstate information will not be available at this stage. After initialization, page framework loads the view state for the page. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests. It contains the state of the controls the last time the page was processed on the server. By overriding LoadViewState() method, component developer can understand how viewstate is restored. Once viewstate is restored, control will be updated with the client side changes. It loads the posted data values. The PostBackData event gives control a chance to update their state that reflects the state of the HTML element on the client. At the end of the posted data changes event, controls will be reflected with changes done on the client. At this point, load event is fired. Key event in the life cycle is when the server-side code associated with an event triggered on the client. When the user clicks on the button, the page posts back.
Page framework calls the RaisePostBackEvent. This event looks up for the event handler and run the associated delegate. After PostBack event, page prepares for rendering. PreRender event is called. This is the place where user can do the update operations before the viewstate is stored and output is rendered. Next stage is saving view state, all the values of the controls will be saved to their own viewstate collection. The resultant viewstate is serialized, hashed, base24 encoded and associated with the _viewstate hidden field. Next the render method is called. This method takes the HtmlWriter object and uses it to accumulate all HTML text to be generated for the control. For each control the page calls the render method and caches the HTML output. The rendering mechanism for the control can be altered by overriding this render method. The final stage of the life cycle is unload event. This is called just before the page object is dismissed. In this event, you can release critical resources you have such as database connections, files, graphical objects etc. After this event browser receives the HTTP response packet and displays the page.