Each request to the Microsoft ASP. NET page processed by Microsoft Internet Information Service (IIS) is handed over to the ASP. net http pipeline. An HTTP pipeline consists of a series of hosted objects that process requests in sequence and convert URLs to plain HTML text. The HTTP pipeline entry is
HttpRuntimeClass. The ASP. NET structure creates an instance of this type for each AppDomain in the auxiliary process. (Note that the auxiliary Process maintains a specific AppDomain for each currently running ASP. NET application .)
HttpRuntimeClass obtained from the internal poolHttpApplicationObject, and arrange this object to process the request. The main task completed by the HTTP application manager is to find the class that will actually process the request. When a. aspx resource is requested, the handler is the page handler, that is,PageThe instance of the inherited class. The associations between resource types and handler types are stored in the application configuration file. More specifically, the default ing set is in the machine. config file.<HttpHandlers>Partially defined. However, applications can customize their own HTTP handler list in the Local web. config file. The following code defines an HTTP handler for. aspx resources.
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>
Extensions can be associated with the handler class, and more are associated with the handler factory class. In all circumstancesHttpApplicationThe object will get an implementationIHttpHandlerInterface object. If the associated resource/class is parsed Based on the HTTP handler, the returned class implements the interface directly. Additional steps are required if the resource is bound to the handler factory. Handler factory implementationIHttpHandlerFactoryInterface.GetHandlerMethod returns an IHttpHandler-based object.
How does the HTTP runtime end this loop and process page requests?ProcessRequestMethod inIHttpHandlerInterface is very important. By calling this method on the object that represents the requested page, ASP. NET structure will start the process that will generate browser output.
Real Page class
The type of the HTTP handler for a specific page depends on the URL. When a URL is called for the first time, a new class is built, which is dynamically compiled into an assembly. The result of checking the analysis process of the. aspx resource is the source code of the class. This class is defined as an ASP Component of the namespace and is assigned a name to simulate the original URL. For example, if the end of a URL is page. aspx, the class name isASP. Page_aspx. However, the class name can be controlled by programming, in@ PageSet in commandClassNameAttribute.
The base class of the HTTP handler isPage. This class defines the minimum set of methods and attributes shared by all page handlers.PageClass implementationIHttpHandlerInterface.
In many cases, the base class of the actual processing program is notPage, But other classes. For example, if code separation is used, this situation occurs. Code separation is a development technology that isolates the Code required for the page into a separate C # and Microsoft Visual Basic. NET classes. The page code is a set of event handlers and helper methods that really determine the page behavior. Available<Script runat = server>Mark this code for inline definition, or place it in an external class (code separation class. The code separation class is fromPageClasses that inherit from and use additional methods are specified as the base class of the HTTP handler.
In another case, the HTTP processing program is not based onPageIn the application configuration file<Pages>ContainsPageBaseTypeAttribute redefinition.
<pages PageBaseType="Classes.MyPage, mypage" />
PageBaseTypeProperty indicates the type and assembly of the base class containing the page handler. SlavePageThe exported class automatically grants the custom method and attribute set of the handler extension.
Page Lifecycle
After fully identifying the HTTP page handler class, ASP. NET will callProcessRequestMethod to process the request. Generally, you do not need to change the implementation of this method because it is composedPageClass.
This implementation will build the control treeFrameworkInitializeMethod.FrameworkInitializeThe method isTemplateControlClass (PageItself) is a protected Virtual Member. All the handlers dynamically generated for. aspx resources will overwriteFrameworkInitialize. In this method, the entire control tree of the page is constructed.
Next,ProcessRequestThe page goes through various stages: initialization, loading view status information and sending back data, loading page user code, and executing the sending back server events. Then, the page enters the display mode: collect updated view status, generate HTML code, and then send the code to the output console. Finally, the page is uninstalled and the request processing is complete.
In each stage, the page triggers a few events that can be intercepted and processed by Web controls and user-defined code. Some of these events are dedicated to embedded controls, so they cannot be processed at the. aspx code level.
The page for processing specific events should clearly register an appropriate handler. However, to be backward compatible with earlier Visual Basic programming styles, ASP. NET also supports implicit event hooks. By default, the page will try to match the specific method name with the event. If the implementation matches, the method is considered to be the handler that matches the event. ASP. NET provides six methods for specific identification of names. They arePage_Init,Page_Load,Page_DataBind,Page_PreRenderAndPage_Unload. These methods are consideredPageClass. During HTTP runtime, these methods are automatically bound to page events, so that developers do not have to write the required bonding code. For examplePage_LoadMethod bound to the pageLoadEvent, you can save the following code.
this.Load += new EventHandler(this.Page_Load);
Automatic Identification of specific names@ PageCommandAutoEventWireupProperty Control. If this attribute is set to false, all applications that want to handle the event need to explicitly connect to the page event. Page performance is slightly better if you do not use auto-binding events, because no additional name or event matching is required. Note that all Microsoft Visual Studio. NET projects are disabledAutoEventWireupProperty. However, the default setting of this attribute is true, that isPage_LoadMethods are identified and bound to associated events.
The following table lists several stages of page execution in sequence. The execution marks application-level events and/or protected and override methods.
Table 1: key events in ASP. NET page Lifecycle
| Phase |
Page events |
Covered methods |
| Page Initialization |
Init |
|
| Load view status |
|
LoadViewState |
| Process the returned data |
|
Arbitrary implementationIPostBackDataHandlerInLoadPostDataMethod |
| Load page |
Load |
|
| Send a change notification |
|
Arbitrary implementationIPostBackDataHandlerInRaisePostDataChangedEventMethod |
| Handle sending back events |
Any sending event defined by the Control |
Arbitrary implementationIPostBackDataHandlerInRaisePostBackEventMethod |
| Pre-display stage |
PreRender |
|
| Save view status |
|
SaveViewState |
| Display page |
|
Render |
| Uninstall page |
Unload |
|
Some of the stages listed above are invisible at the page level, and are only for Server Control writers andPageThe exported class developer makes sense.Init,Load,PreRender,UnloadAnd all the sending events defined by the embedded control constitute the stages of the sending page.
Stages of execution
The first stage in the page lifecycle is initialization. The mark of this stage isInitEvent. After the control tree of the page is successfully created, this event is triggered on the application. In other words, whenInitWhen an event occurs, all controls declared statically in the. aspx source file are instantiated and Their default values are used. Controls can be interceptedInitEvents to initialize all settings required for the lifecycle of the incoming Web request. For example, the control can load an external template file or set the event handler. Note that the view status information is not available.
After initialization, the page framework loads the view status of the page. View status is a set of name/value pairs. In this collection, the control and page itself store all information that must always be valid for all Web requests. The view status indicates the call context of the page. Generally, it contains the status of the controller when the page was last processed on the server. When a page is requested for the first time in a session, the view status is empty. By default, view status is stored in hidden fields that are silently added to the page. The field name is_ VIEWSTATE. OverwriteLoadViewStateMethod (ControlClass), component developers can control the storage mode of the view status and the way the view status content is mapped to the internal status.
Some methods (suchLoadPageStateFromPersistenceMediumAnd its correspondingSavePageStateToPersistenceMediumTo load the view status and save it to other storage media (such as sessions, databases, or server files. AndLoadViewStateDifferent, the above method can only bePageUsed in the exported class.
After the view status is stored, the status of the control in the page tree is the same as that shown in the browser for the last time. The next step is to update their status to add changes to the client. The control has the opportunity to update its status in the data sending and sending process, so as to accurately reflect the status of corresponding HTML elements on the client. For exampleTextBoxThe HTML element corresponding to the control is<Input type = text>. In the send-back data phase, the TextBox Control retrieves the current value marked with <input> and uses this value to refresh its internal status. Each control extracts values from the returned data and updates some of its attributes.TextBoxControl will update itsTextAttribute, andCheckBoxControl will refresh itsCheckedAttribute. The ing between server controls and HTML elements can be found through the IDs of the two.
At the end of the data re-sending phase, the status of all controls on the page will be updated using changes entered by the client. At this time, the page will be triggeredLoadEvent.
Some controls may exist on the page. When a specific sensitive property is modified in two different requests, a specific task needs to be completed. For example, ifTextBoxThe control text is modified on the client.TextChangedEvent. Each control can trigger an event when one or more of its properties are modified to the value entered by the client. Controls that are critical to these changes are implementedIPostBackDataHandlerInterface.LoadPostDataThe method is inLoadCalled immediately after the event. ThroughLoadPostDataThe control verifies whether a key change has occurred since the last request and triggers its own change event.
The key event in the page lifecycle is the event called to execute the server code. This code is associated with the event triggered by the client. When you click the button, the sending back page is displayed. The set of return values includes the ID of the button that starts the entire operation. If the control is implementedIPostBackEventHandlerInterface (such as button and link button), the page framework will callRaisePostBackEventMethod. The behavior of this method depends on the type of the control. This method searches for buttons and links.ClickEvent handler and run related delegation.
After the event is returned, the page is displayed. The mark of this stage isPreRenderEvent. The control can use this time to perform the update operations that need to be performed before the view status is saved and the output is displayed. The next status isSaveViewStateIn this status, all controls and pages will update themselves.ViewStateSet content. The status of the serialized, hashed, and Base64 encoded view is obtained. The view status is associated with the hidden field _ VIEWSTATE.
OverwriteRenderMethod To change the display mechanism of each control. This method accepts the HTML writer object and uses this object to accumulate all the HTML text to be generated for the control.PageClassRenderBy default, the method includes recursive calls to all member controls. For each control, the page will callRenderMethod, and cache HTML output.
The last mark in the page isUnloadEvent that occurs before the Page Object is deleted. In this event, you should release all key resources (such as files, graphical objects, and database connections) that may be occupied ).
After this event, the browser receives the HTTP response packet and displays the page.
Summary
The ASP. NET page object model is extremely novel and unique due to its event mechanism. Web pages are composed of controls that can generate rich HTML-based user interfaces and interact with users through events. Previously, setting event models in the context of Web applications was challenging. We are surprised to see that the events generated by the client can be solved by the server code, and the same HTML page can still be output after only some corresponding modifications are made.
Understanding this model is very important to understand the various stages of the page lifecycle and how page objects are instantiated and used by HTTP runtime.