ASP.NET request processing mode

xiaoxiao2021-03-06  52

Traditional server scripting languages, such as ASP, JSP, etc., write server scripts, are small and small, are embedded in HTML interpretation or compile execution, execute these code by the server platform to generate HTML; for this similar script, page The living cycle is actually very simple, that is, from the beginning to the end, execute all the code, of course, servlet written in Java can write more complex code, but from the structure, and JSP is nothing difference.

The appearance of ASP.NET breaks this tradition; ASP.NET uses CodeBeHind technology and server-side controls, joining the concept of server-side events, changing the mode written in the scripting language, closer to Window programming, making web programming more simple , Intuitive; but we have to see that ASP.NET itself does not change the basic model of web programming, just encapsulates some details, providing some easy-to-use functions, making code easier to write and maintain; from some extent The way the server is executed is complicated, which is the main body we have to discuss today: ASP.NET Web Page's survival cycle.

Third, ASP.NET request processing mode

We said that the web page of the ASP.NET does not leave the web programming mode, so it is still in request -> receiving request -> processing request -> Sending the pattern in this mode, each time with the client interaction will trigger once A new request, so a Web Page is based on a request.

When IIS receives the request from the client, the request will be handed over to the process of the ASPNET_WP. This process will view if the requested application domain exists. If there is no existence, create one, then create an HTTP runtime (httpruntime) ) To process requests, this runtime "provides a set of ASP.NET runtime services for the current application" (from MSDN).

HTTPRUNTIME will maintain a series of applications instances when processing the request, which is an instance of the Global.asax, which will be stored in an application pool when there is no request (actually The application pool is maintained by another class. HTTPRuntime is just a simple call), and each receives a request, HTTPRuntime gets an idle instance to handle the request. This instance does not handle other requests before the request, after processing It will return to the pool again, "An instance is used to handle multiple requests during its survival, but it can only handle one request at a time." (From MSDN)

When the application instance handles the request, it creates an instance of the request page class, executes its processRequest method to handle the request, which is the beginning of the Web Page lifecycle.

Fourth, ASPX page with codebehind

Before you understand the life cycle of the page, let's explore some relationships between ASPX and CodeBehind.

<% @ Page language = "c #" codebehind = "Webform.aspx.cs" inherits = "mynamespace.webform"%>%>

I believe friends who have used Codebehind technology, this sentence to the top of ASPX should be very familiar, let's have an analysis:

Page language = "c #" This doesn't have to say more, codebehind = "WebForm.aspx.cs" This sentence represents the binding code file

Inherits = "mynamespace.webform" This sentence is very important, it indicates the class name of the page inheritance, that is, the class in the code file in CodeBehind, this class must be derived from system.web.webcontrols.page

From above we can analyze, in fact, CodeBehind is the base class of page (ASPX), here, some friends may ask, when writing ASPX, it is completely embedded in HTML in HTML when writing ASPX Or embed server control, didn't see the so-called "class" shadow?

This problem is actually not complex, friends using ASP.NET programming can go to your system disk: /Windows/microsoft.net/framework/ / Temporary ASP.NET FILES in this directory, this below The temporary file of the ASP.NET application existing on this unit is the name of the application, then go back to the two layers (to ensure unique, ASP.NET automatically generates two layers of subdirectory, and subdirectory The name is randomly), then we will find a lot of link libraries such as "YFY1GJHC.DLL", "Xeunj5u3.dll" and "Komee-bp.0.cs", "9falckav.0.cs" Document, in fact, this is the result of AspX being dynamically compiled by ASP.NET, open these source files. We can find:

Public class Webform_ASPX: MyNamespace.Webform, System.Web.SessionState.irequiresSessionState

This has confirmed our previous statement. Aspx is a subclass of code binding classes. Its name is an ASPX file name plus the "_aspx" suffix. By studying these code we can find that the server control defined in all ASPX is actually defined in all ASPX They are all generated in these codes, and then dynamically generate these codes, the code originally embedded in the ASPX is written in the corresponding position.

When a page is first accessed, the HTTP runs with a code generator to parse the ASPX file and generate source code and compile, then the subsequent access directly calls the compiled DLL, which is why ASPX A very slow reason when visiting is visited.

Explain this problem, let's see another question. When we use the code binding, we drag a control in the design page, then switch to the code view, you can use this control directly in Page_Load, since the control is generated in the subclass, why can you be in the parent class? Direct use?

In fact, we can find that whenever you drag a control to the page with vs.net, you will always add a declaration like this:

protected system.web.webcontrols.button button1;

We can find that this field is declared into protected, and the name is consistent with the ID of the control in the ASPX. If you think about it, this question is unlucky. The source code of the ASPX mentioned in front of us is dynamically generated and compiled by the generator. The generator will generate the code of each server control. When it is generated, it will check that the parent class declares this control, if declares It will add a code similar to the following:

This.dataGrid1 = __ctrl; this __ctrl is the variable of the control, which gives the reference to the control to the corresponding variables in the parent class, which is why the statement in the parent class must be protected (actually For public), because the subclass is to be invoked.

Then when executing Page_Load, because the parent class's statement has been assigned a value in the initialization code in the subclass, we can use this field to access the corresponding control, understand these, we will not commit the code tied Use a control in the constructor in the file, causing an error in the empty reference, because the constructor is executed first, this time the initialization of the subclass has not started, so the fields in the parent class are null value, as the child When is the class initializes us to put it on the discussion.

V. Page survival cycle

Now returned to the content mentioned in the third title, we told the instance of HTTPApplication's instance to receive requests, and create an instance of page classes. In fact, this instance is an instance of the class of dynamically compiled ASPX, in the previous title Understanding the ASPX is actually a subclass of the class binding class, so it inherits all protected methods.

Now let's take a look at the code of the CodeBehind class that vs.net automatically generated, and starts our discussion of the page life cycle:

#Region Web Form Designer Generated Code

Override protected void oninit (Eventargs E)

{

//

// Codegen: This call is necessary for the ASP.NET Web Form Designer.

//

InitializationComponent ();

Base.onit (E);

}

///

/// Designer supports the required method - do not use the code editor to modify

/// This method is content.

///

Private vidinitiRizeComponent ()

{

This.DataGrid1.itemdatabase.DataGriditeMeventHndler (THISDATAGRID1_ITEMDATABOUND);

This.Load = New System.EventHandler (this.page_load);

}

#ndregion

This is the code generated by VS.NET. Let's look, there are two ways, one is oninit, one is initializeComponent, the latter calls the former, actually this is the beginning of the page, in InitializeComponent See the control's event declaration and page's LOAD declaration.

Below is a description of a paragraph extracted from the MSDN and a sequence table for a page lifecycle method and event trigger:

"Each time you request an ASP.NET page, the server will load an ASP.NET page and uninstall this page when the request is completed. The page and the server control is responsible for performing the request and rendering HTML to the client. Although the client Communication between the server is stateless and intermittent, but the customer must feel that this is a continuous process. "

"This continuity illusion is implemented by the ASP.NET page framework, page and its control. After returning, the behavior of the control must appear to begin from the last web request. Although the ASP.NET page frame To make the execution status management is relatively easy, but in order to obtain continuous effects, the control developer must know the execution order of the control. Control developers need to know: What information can be used in various stages of the control life cycle, which data, controls Which state is presented. For example, the control cannot call its parent before the control tree on the pages. "" The following table provides advanced overview of each stage in the control life cycle. For more information, click on the link in the table "

The method or event initialization initialization of the operation to be overwritten in phase control needs to initialize the settings required in the incoming Web request lifecycle. See Handling Inherited Events. INIT Event (OnInit Method) Loading View Status At the end of this phase, you will automatically populate the ViewState properties of the control, see Introduction to the status in the maintenance control. The control can rewrite the default implementation of the loadViewState method to restore custom status. The loadViewState method handles the return data processing incoming form data and updates the property accordingly. See Processing the return data.

Note that only controls that process the return data are involved in this stage. LoadPostData method

(If IPOSTBACKDATAHANDLER is implemented) Load all requests, such as setting up database queries. At this point, the server control in the tree has been created and initialized, the state is restored and the form control reflects the client's data. See Handling Inherited Events. LOAD event

(ONLOAD method) Send a return change notification to initiate changes between the changes between the current and previous rapids. See Processing the return data.

Note that only controls that trigger a return change event participate in this phase. RaisePostDataChangeDevent method

(If IPOSTBACKDataHandler) Processing the return event process, the retraced client event is caused, and the corresponding event is triggered on the server. See Capturing a return event.

Note that only controls that process the retrace event participate in this phase. RaisePostBackevent method

(If you have implemented ipostbackeventhandler) Pre-predicts any updates before rendering output. You can save the changes made to the control status during the pre-presentation phase, and the changes in the rendering phase will be lost. See Handling Inherited Events. Prerender event

(OnPrender Method) Save Status After this phase, keep the ViewState properties of the control to the string object. This string object is sent to the client and sent back as a hidden variable. To improve efficiency, the control can override the SaveViewState method to modify the ViewState property. See the status in the maintenance control. The SaveViewState method presents generation to present the output to the client. See Rendering the ASP.NET Server Control. The render method disposes all the final cleaning operations before the destruction control. The reference to expensive resources must be released at this stage, such as database links. See the method in the ASP.NET server control. Dispose method Uninstall all final cleaning operations before performing destruction controls. Controls The authors are typically cleared in Dispose without processing this event. UNLOAD event (on unload method)

From this table we can clearly see a method and trigger time from loaded to the uninstallation, and then we will analyze it in depth.

I saw the table above, the careful friend may ask, since OnNit is the beginning of the page lifecycle, and we talk about the control in the subclass in the subclass, then here in the InitializeComponent method. It is already possible to use the fields in the parent class, then it means that the initialization of the subclass is more before. In the third title, we told the page class ProcessRequest to the beginning of the real page declaration cycle, this method is called by httpApplication (where the call is more complicated, there is a chance to write a text), a PAGE The process of request is to start from this method, to view the source code by anti-compiling .NET class libraries, we discover the base class in System.Web.WebControls.page: System.Web.WebControls.templateControl (it is a page and user control The base class defines a "frameworkInitialize" virtual method, and then call this method in the PROCESSREQUEST, and we discover the trace of this method in the source code generated by the generator. All controls are This method is initialized, the control tree of the page is generated at this time.

The next thing is simple, we come to gradually analyze each item of the page life cycle:

1, initialization

Initialize the INIT event and the oninit method corresponding to Page.

If you want to rewrite, the MSDN recommended by the MSDN is to overload the OnInti method, rather than adding an agent of an init event. The two are different. The former can control the order in which the parent class OnNit method is controlled, and the latter can only be in the parent class. After the onInit, execute (actually being called inside onInit).

2, load the view status

This is a more important way, we know that for each request, it is actually processed by different page class instances. In order to ensure the state between the two requests, ASP.NET uses ViewState, and the description of ViewState, please Reference I have another article:

http://expert.9cbs.net/expert/topic/1558/1558798.xml?temp=.2561609

The LoadViewState method is to get the last state from ViewState, and follow the structure of the page of the page, returning the entire tree with the return to the entire tree, and restores the corresponding state to each control.

3. Treatment of return data

This method is to check whether the status of the control data sent back by the client has changed. Prototype of the method:

Public Virtual Bool LoadPostData (String PostDataKey, NameValueCollection PostCollection)

PostDataKey is a keyword that identifies the control (the key in PostCollection). PostCollection is a collection of retrace data, we can override this method, then check if the return data has changed, if so, returns a True, "If the control status changes due to retrace, LoadPostData returns true; otherwise returns false. Page Frame Tracking all controls returned to True and call RaisePostDataChangeDevent on these controls." (Excerpted from MSDN)

This method is defined in System.Web.WebControls.Control, and all methods that need to handle the custom control of the event requires processing. For the Page we discussed today, you can use it. 4, load

Load the corresponding Load event and the online method, for this event, I believe that most friends will be more familiar, using the page_load method in the page generated by vs.net is the method of responding to the LOAD event, for each request, the Load event trigger, Page_Load method It will also be implemented, I believe this is also the first step in which most people understand the ASP.NET.

The page_load method responds to the Load event, this event is defined in the System.WebControl.Control class (this class is the ancestors of the Page and all server controls) and is triggered in the OnLoad method.

Many people may encounter such things, write a PageBase class, then to verify user information in Page_Load, and find that no matter whether it is successful, the subclass page will always be executed, this time is likely to leave some Safety risks, users may perform Page_Load methods in subclasses without obtaining verification.

This problem is very simple because the Page_Load method is added to the Load event in the OnNit, and the onInit method of the subclass is added to the LOAD event first, then call Base.onIn, which causes the subclass. Page_load is added first, then execute it first.

It is also very simple to solve this problem, there are two ways:

1) Remove the ONLOAD method in PageBase, then verify the user in ONLOAD, then call Base.onLoad, because the Load event is triggered in ONLOAD, so we can guarantee that the user can be verified before triggering the Load event.

2) Call BASE.ONINIT first in the onInit method of the subclass, so that the parent class will perform Page_Load first

5, send a return change notification

This method corresponds to the process of processing step 3. If the processing return data returns true, the page framework calls this method to trigger the event of the data change, so the reputation of the custom control will trigger in this method. .

Similarly, this method is not too big for Page. Of course, you can also define the events of data changes on the basis of Page, which is of course possible.

6, handling the rapid process

This method is where most server control events are ranging. When the request contains the information triggered by the control event (the server control is another topic, I will discuss the discussion in the next future), the page control calls the corresponding control RaisePostBacke Method to initiate events of server-side.

Here is a common problem:

Regardless of netizens asked, why there is no change in data after submission

Most cases are the trigger flow of the server event. We can see that the trigger server event is after Page LOAD, that is, the page will execute Page_Load before executing the button (here as an example of the button) Click on events, many friends bind data in Page_Load, then process changes in the button event, doing a problem, Page_Load will always be executed before the button event, then it means that the data has not been changed, and Page_Load The code binded by the data is executed first. The original data is assigned to the control. When the button event is executed, the original data is actually obtained, then the update is of course no effect. Change this question is also very simple, relatively reasonable to write code binding code into a method, we assume Binddata:

Private void binddata ()

{

// Binding data

}

Then modify the PageLoad:

Private Void Page_Load (Object Sender, Eventargs E)

{

IF (! ispostback)

{

Binddata (); // Bind data when the page is accessed

}

}

Finally, in the button event:

Private Button1_Click (Object Sender, Eventargs E)

{

//update data

BindData (); // Re-bound data

}

7, pre-presented

Both the final request will change to the response of the sendback server, and the pre-presentation is to perform changes to the status of the status before the final presentation, because before presenting a control, we must generate HTML according to its properties, such as style properties, This is the most typical example. Before pre-presented, we can change the style of a control. When performing pre-presend, we can save Style as the style information of HTML as the rendering phase.

8, save the status

This stage is for loading state, we have repeatedly mentioned that the request is different instances in processing, so we need to save the status of this page and control, which is the stage of writing the status to ViewState.

9, presentation

Here, in fact, the processing of the requested page will basically tell, in the render method, the control tree of the entire page will be recursively called, and the render method is called, and the corresponding HTML code is written to the final response stream.

10, disposal

In fact, the Dispose method is released at this stage, such as database connections.

11, uninstall

Finally, the page will perform the onunload method to trigger the unload event. Processing before the page object is destroyed, actually ASP.NET provides this event only design considerations, usually the release of resources will be completed in the Dispose method, so this method Also become a chicken rib.

We briefly introduce the survival cycle of the page. For the processing of server-side events, we have made a less in-depth explanation. Today, it is mainly to understand the cycle of the page execution. I will follow the server controls and the survival period I will write some. Discussion on the article.

These content is some of my experience in Page research when I study asp.net. The specific details are not very detailed. For more details, please refer to MSDN, but I raised some errors and errors that occurred by beginners. The reason, I hope I can bring you inspiration.

转载请注明原文地址:https://www.9cbs.com/read-83315.html

New Post(0)