ASP.NET Web Page in-depth discussion

xiaoxiao2021-03-06  87

First, the server script foundation

First, let's review the basic implementation of the web server page first:

1. The client sends a request to the server by typing the address in the address bar of the browser.

2. After the server receives the request, send the corresponding server-side page (which is the script) to execute, the script generates the client's response, send back to the client

3. The client browser receives the response of the server, parsing the HTML, presented the graphical web page in front of the user.

For the interaction of the server and client, usually by the following main ways:

1, form: This is the most important way, standardized controls to get the user's input, Form's submission will send data to server-side processing

2, querystring: By transmitting parameters to the server by rear the parameters after the URL, this method is actually the same as the GET method.

3, cookies: This is a relatively special way, usually used for user identity confirmation

Second, ASP.NET

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 , Complicate the way the server is executed, this is the main body we want to discuss today: ASP.NET

The survival cycle of the web page.

Third, ASP.NET request processing mode

We said that the web page of the ASP.NET has not been separated from the web programming mode, so it is still requested -> Receive Request -> Send Response -> Send Response

Such modes are working, each time with the client's interaction, triggers a new request, so a lifecycle of a web page is based on one 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 handle requests, this runtime "provides a set of current applications

ASP.NET Runtime Services "(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 example is used to handle multiple requests during its survival, but it can only handle a request at a time." (Excerpted from MSDN) When the application instance handles the request, it will Create an instance of the request page class, execute its processRequest method to process the request, this method is the web

The beginning of the Page life cycle.

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 is not 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 of the codebehind, which 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 who use Asp.net programming can go to your system disk: /Windows/Microsoft.Net/framework/ / Temporary

ASP.NET

In this directory, this below puts the temporary file of the ASP.NET application on this unit, the name of the subdirectory 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 names are random), then we will find a lot of link libraries like "Yfy1gjhc.dll", "Xeunj5u3.dll", "Komee-bp.0.cs", " 9falckav.0.cs "This source file is actually the result of Aspx after being dynamically compiled by ASP.NET, and 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 a variable that generates the control. At this time it assigns 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 available for public), because Guaranteed subclasses can be called.

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.itemdatabaseTeM.Web.ui.WebControls.DataGriditeMeventHandler (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:

"Every time you ask an ASP.NET page, the server will load an ASP.NET.

Page and uninstall this page when the request is completed. Page and its server controls are responsible for performing requests and html

Present it to the client. Although the communication between the client and the server is stateless and intermittent, the customer must feel that this is a continuous process. "

"This continuous illusion is implemented by the ASP.NET page frame, page and its control. After fur, the behavior of the control must appear from the last Web

The request ended the place. Although ASP.NET

The page frame allows execution status management to be 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 the control life cycle, which data can be used, which is held when the control is presented. For example, the control cannot call its parent before the control tree on the population page. "

"The following table provides advanced overview of each stage in the control life cycle. For more information, click on the link in the table."

stage

The control needs to be executed

Method or events to be rewritten

initialization

Initialization is incorporated into the settings required for the life cycle. See Handling Inherited Events.

INIT events

Load view status

At this stage, the ViewState property of the control is automatically populated, see the introduction in the status in the maintenance control. Controls can be rewritten

The default implementation of the LoadViewState method is restored in custom status.

LoadViewState method

Treatment of return data

Process the incoming form data and update the attribute accordingly. See Processing the return data.

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

LoadPostData method

(If you have realize iPostBackDataHandler)

load

Perform all requests a shared operation, such as setting up a database query. 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

Change changes to the status change 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 you have realize iPostBackDataHandler)

Processing

Processing a retraided client event and triggeting the corresponding event 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 enabled ipostbackeventhandler)

Pre-presentation

Perform any updates before presenting the 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)

Saving status

After this stage, automatic viewState of the control

The property remains in the string object. This string object is sent to the client and sent back as a hidden variable. In order to improve efficiency, the control can be rewritten

SaveViewState method to modify the ViewState property. See the status in the maintenance control.

SaveViewState method

Present

Generates the output presented to the client. See Rendering the ASP.NET Server Control.

Render method

Disposition

Perform all final cleaning operations before destruction control. The reference to expensive resources must be released at this stage, such as database links. See ac. ASP.NET

Method in server controls.

Dispose method

Uninstall

Perform all final cleaning operations before destruction control. 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 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 retracence,

LoadPostData returns true; otherwise returns false. Page Framework Tracking All Controls that return TRUE and call them on these controls

RaisePostDataChangeDevent. (Taken 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)

Reload 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 ensure 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.

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

New Post(0)