In this article we will explore the ASP.Net page events and stages which are part of page life cycle. Before we go ahead i would like to review what we have learnt so far in previous articles related to ASP.Net.
IIS: IIS (Internet Information Server) is a Microsoft Web server that makes it possible to quickly and easily deploy powerful Web sites and applications. 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. (By default, ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.)
- If a file name extension has not been mapped to ASP.NET, ASP.NET will not receive the request. It will be handled by the IIS. The requested page/image/file is returned without any processing.
- If you create a custom handler to service a particular file name extension, you must map the extension to ASP.NET in IIS and also register the handler in your application’s Web.config file.
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_WP.EXE: 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. When a web page is requested, IIS looks for the application pool under which the current application is running and forwards the request to the respective worker process.
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
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.
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
<httpHandlers> 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.
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>
HttpApplicationFactory: Its main task consists of using the URL information to find a match between the virtual directory of the URL and a pooled
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 include 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.
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 a .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.
In brief, here is the explanation of what happen to request when it arries at IIS
- Web page request comes from browser.
- IIS maps the ASP.NET file extensions to ASPNET_ISAPI.DLL, an ISAPI extension provided with ASP.NET.
- ASPNET_ISAPI.DLL forwards the request to the ASP.NET worker process (ASPNET_WP.EXE or W3P.EXE).
- ISAPI loads
HTTPRuntimeand passes the request to it. Thus, HTTP Pipelining has begun.
HttpApplicationFactoryto either create or reuse the
HTTPContextfor the current request.
HTTPRuntimealso maps the
HTTPApplicationwhich handles the application level events.
HTTPModulesfor the page requests.
HTTPHandlerfor the page request. This is the last stage of
HTTPHandlersare responsible to process request and generate corresponding response messages.
- Once the request leaves the
HTTPPipeline, page level events begin.
- Page Events like load etc happens at this stage.
HTTPHandlergenerates the response with the above events and sends back to the IIS which in turn sends the response to the client browser.
ASP.Net page life cycle
ASP.Net page life cycle and stages involved several page stages and page events when it was triggered by HTTPHandler.Please not that there are Application stages which occurs before and after page life cycle which are discussed here.
Page goes through the several stages mentioned below alone with the description of each stage.
|Page request||The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.|
|Start||In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.|
|Initialization||During page initialization, controls on the page are available and each control’s UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.|
|Load||During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.|
|Postback event handling||If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.|
|Rendering||Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page’s Response property.|
|Unload||The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.|
Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.
Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true, page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web Server Control Event Model.
Below are the page life-cycle events that you will use most frequently..
|Page Event||Typical Use|
|PreInit||Raised after the start stage is complete and before the initialization stage begins.Use this event for the following:
Note : If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
|Init||Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.Use this event to read or initialize control properties.|
|InitComplete||Raised at the end of the page’s initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.Use this event to make changes to view state that you want to make sure are persisted after the next postback.|
|PreLoad||Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.|
|Load||The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.Use the OnLoad event method to set properties in controls and to establish database connections.|
|Control events||Use these events to handle specific control events, such as a Button control’s Click event or a TextBox control’s TextChanged event.
Note : In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
|LoadComplete||Raised at the end of the event-handling stage.Use this event for tasks that require that all other controls on the page be loaded.|
|PreRender||Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.|
|PreRenderComplete||Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.|
|SaveStateComplete||Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.|
|Render||This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control’s markup to send to the browser.If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.|
|Unload||Raised for each control and then for the page.In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
Note : During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.
Those who want to go in depth study for life cycle events may explore msdn where you will find more than enough information what you are looking for.The next article “All about patterns” of this series is bit different in the sequence of the series i was writing under .Net Concepts category on this blog.
In next my next article”All about patterns” i would like to take the opportunity to explore different kind of patterns and further series will include in depth study of MVC and MVVM architectural patterns.Once we finished pattern series we will further explore asp.net internals and other features.