In-depth exploration of ASP. NET web page applications

Source: Internet
Author: User

I. server script Basics

First, let's review the basic execution method of the Web Server Page:

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

2. After the server receives the request, it sends it to the corresponding Server Page (that is, the script) for execution. The script generates the client response and sends it back to the client.

3. The client browser receives a response from the server, parses the HTML, and displays the graphical web page in front of the user.

For the interaction between the server and the client, the following methods are usually used:

1. Form: This is the most important method. Standard controls are used to obtain user input. Form submission sends data to the server for processing.

2. querystring: Pass the parameter to the server by adding a parameter after the URL. This method is the same as form in get mode.

3. Cookies: this is a special method, which is usually used for user identity confirmation.

II. Introduction to ASP. NET

Traditional server scripting languages, such as ASP and JSP, are similar in writing server scripts. They are embedded in HTML for interpretation or compilation and execution.CodeThe server platform executes the code to generate html. For such scripts, the page life cycle is actually very simple, that is, from the beginning to the end, all the code is executed, of course, Servlet compiled in Java can write more complex code, but in terms of structure, it is no different from JSP.

ASP. the emergence of net breaks this tradition; ASP. net adopts codebehind technology and server-side controls, adds the concept of server-side events, changes the script language writing mode, and is closer to Window Programming, making web programming simpler and more intuitive; but we can see that ASP. net does not change the basic web programming mode, but encapsulates some details and provides some easy-to-use functions to make the code easier to write and maintain. To some extent, the method of server execution is complicated. This is the subject that we will discuss today: Asp. net web page lifecycle.

Iii. ASP. NET Request processing mode

Let's say, Asp. net web page is not in the Web programming mode, so it is still working in the request-> receive request-> process request-> send response mode, every interaction with the client triggers a new request. Therefore, the lifecycle of a Web page is based on a single request.

When IIS receives a request from the client, it will send the request to the aspnet_wp process for processing. This process will view the requested application.ProgramWhether the domain exists. If it does not exist, one is created, and an HTTP Runtime (httpruntime) is created to process the request. This RunTime "provides a set of ASP for the current application. net runtime Service (from msdn ).

Httpruntime maintains a series of application instances when processing requests, that is, the global class of the application (Global. asax) instances. These instances are stored in an application pool when there is no request (in fact, the application pool is maintained by another class, And httpruntime is just a simple call ), every time a request is received, httpruntime will get an idle instance to process the request. This instance will not process other requests before the request ends. After the request is processed, it will return to the pool, "An instance is used to process multiple requests within its lifetime, but it can only process one request at a time." (From msdn)

When an application instance processes a request, it creates an instance of the Request page class and executes its processrequest method to process the request. This method is the beginning of the web page lifecycle.

4. ASPX page and codebehind

Before getting to know the lifecycle of the page, we will first discuss the relationship between aspx and codebehind.

<% @ Page Language = "C #" codebehind = "webform. aspx. cs" inherits = "mynamespace. webform" %>

I believe that my friends who have used codebehind technology should be very familiar with this sentence at the top of Aspx. Let's analyze it one by one:

Page Language = "C #".

Codebehind = "webform. aspx. cs" indicates the bound code file.

Inherits = "mynamespace. webform is very important. It indicates the class name inherited by the page, that is, the class in the codebehind code file. This class must be from the system. web. webcontrols. page Derivation

From the above analysis, we can see that the classes in codebehind are actually the base classes of the page (aspx). Some friends may ask, when writing aspx, I embed code in HTML or server controls completely in ASP mode. I didn't see the so-called "class" shadow?

This problem is actually not complex. You can use ASP. NET Programming friends can go to your system disk: \ windows \ Microsoft. net \ framework \ <version> \ temporary ASP. under the. NET Files directory, all ASP files on the local machine are stored below.. NET application temporary file. The subdirectory name is the name of the application, and then two layers (to ensure uniqueness, Asp. net automatically generates two sub-directories with random sub-Directories), and then we will find many similar: "yfy1gjhc. DLL, xeunj5u3. DLL and the "komee-bp.0.cs", "9falckav. 0. CS "source file, in fact this is aspx is ASP. NET Dynamic compiled results, open these source files we can find:

Public class webform_aspx: mynamespace. webform, system. Web. sessionstate. irequiressessionstate

This confirms our previous statement that aspx is a subclass of the code binding class. Its name is the aspx file name with the suffix "_ aspx". By studying these codes, we can find that, in fact, all server controls defined in aspx are generated in these codes. When these codes are dynamically generated, the Code originally embedded in aspx is written in the corresponding position.

When a page is accessed for the first time, an HTTP code generator is used to parse the aspx file and generateSource codeCompile and then directly call the compiled DLL for later access. This is why the first access to aspx is very slow.

After explaining this question, let's look at another question. When binding code, drag a control on the design page and switch to the Code view to directly use the control in page_load. Since the control is generated in the subclass, so why can I use it directly in the parent class?

In fact, we can find that every time vs. NET is used to drag a control to the page, the code binding file will always add a declaration like this:

Protected system. Web. webcontrols. Button button1;

We can find that this field is declared as protected, and its name is the same as the ID of the control in Aspx. Think about it carefully and this problem will be solved. As mentioned above, the source code of aspx is dynamically generated and compiled by the generator. The generator will generate the code for dynamically generating each server control, it checks whether the parent class declares the control. If it declares the control, it adds a code similar to the following:

This. Maid;

This _ CTRL is the variable that generates the control. At this time, it assigns the reference of the control to the corresponding variable in the parent class, this is also why the declaration in the parent class must be protected (or public), because the subclass must be called.

Then, when executing page_load, because the declaration of the parent class has been assigned a value for the initialization code in the quilt class, we can use this field to access the corresponding control and learn about it, we will not commit the mistake of using controls in the constructor in the code binding file, resulting in null reference exceptions, because the constructor is the first to execute, and the initialization of the subclass has not yet started, therefore, the field in the parent class is null. We will discuss the time when the subclass is initialized.

5. Page Lifecycle

Now back to the content mentioned in the third title, we talked about the httpapplication instance receiving requests and creating page class instances, in fact, this instance is an instance of the dynamically compiled aspx class. In the previous title, we learned that aspx is actually a subclass of the class in code binding, so it inherits all the protected methods.

Now let's take a look at the codebehind class code automatically generated by vs. Net to start our discussion on the page lifecycle:

# Region web form designer generated code

Override protected void oninit (eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
Initializecomponent ();
Base. oninit (E );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>

Private void initializecomponent ()
{
This. Maid + = new system. Web. UI. webcontrols. Maid (this. Maid );

This. Load + = new system. eventhandler (this. page_load );
}

# Endregion

This is to use. NET page code. We can see that there are two methods, one is oninit and the other is initializecomponent, and the latter is called by the former. In fact, this is the beginning of page initialization, in initializecomponent, we can see the control event Declaration and the page load declaration.

The following is a description extracted from msdn and a sequence table of page lifecycle methods and event triggering:

"Each time an ASP. NET page is requested, the server will load an ASP. NET page and uninstall the page when the request is complete. The page and its server control are responsible for executing the request and rendering the HTML 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 execution process ."

"The illusion of continuity is implemented by the ASP. NET page framework, pages, and controls. After sending the API back, the control action must start from the end of the last Web request. Although the ASP. NET page framework makes execution status management easier, control developers must know the execution sequence of controls to achieve continuity. Control developers need to know: in each stage of the control lifecycle, what information can be used by the Control, what data can be maintained, and what status the control is in when presented. For example, the control cannot call its parent level before filling the control tree on the page ." "The following table provides an advanced overview of each stage of the control lifecycle. For more information, click the link in the table ."

Phase Operations to be performed by the Control Method or event to be overwritten
Initialization Initialize the settings required during the lifecycle of the incoming Web request. See process inherited events. Init event (oninit method)
Load view status The viewstate attribute of the control is automatically filled at the end of this phase. For details, see the description of the status in the maintenance control. Controls can override the default implementation of the loadviewstate method to restore a custom state. Loadviewstate Method
Process the returned data Process input form data and update properties accordingly. See process sending back data.
Note that only the control that processes the returned data participates in this phase.
Loadpostdata method (if ipostbackdatahandler has been implemented)
Load Perform common operations for all requests, such as setting database queries. In this case, the server control in the tree has been created, initialized, and restored, and the Form Control reflects the client data. See process inherited events. Load event
(Onload method)
Send a change notification A change event is triggered to respond to status changes between the current and previous sending. See process sending back data.

Note that only the control that triggers the send-back change event participates in this phase.

Raisepostdatachangedevent Method
(If ipostbackdatahandler has been implemented)
Handle sending back events Process client events that cause sending back, and trigger corresponding events on the server. See capture sending back events.

Note that only the control that handles the send-back event participates in this phase.

Raisepostbackevent Method
(If ipostbackeventhandler has been implemented)
Pre-rendering Execute any update before rendering the output. Changes made to the control status during the pre-rendering phase can be saved, while changes made during the rendering phase will be lost. See process inherited events. Prerender event
(Onprerender method)
Save status After this phase, the viewstate attribute of the control is automatically kept in 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 attribute. See maintain the status in the control. Saveviewstate Method
Rendering Generate the output presented to the client. See rendering ASP. NET Server controls. Render Method
Disposal Execute all final cleanup operations before the control is destroyed. Reference to expensive resources, such as database links, must be released at this stage. See methods in ASP. NET Server controls. Dispose Method
Uninstall Execute all final cleanup operations before the control is destroyed. The control creator usually clears the event in dispose instead of processing the event. Unload event (on unload method)

From this table, we can clearly see the call method and trigger time of a page from loading to detaching. Next we will analyze it in depth.

After reading the table above, a careful friend may ask, since oninit is the beginning of the page lifecycle, we mentioned in the previous section that controls are created in child classes, so here we can actually use the field of the sound name in the parent class in the initializecomponent method, which means that the initialization of the subclass is more before this?

In the third title, we mentioned that the processrequest of the page class is the beginning of the page declaration cycle in the true sense. This method is called by httpapplication (the call method is complex, I have the opportunity to write an article separately). A page is used to process the request through decompilation. net class library to view the source code, we found in the system. web. webcontrols. base class of page: system. web. webcontrols. templatecontrol (which is the base class of the page and user control) defines a "frameworkinitialize" virtual method, and then calls this method in page processrequest first, we found this method in the source code of aspx generated by the generator. All controls are initialized in this method, and the Control tree on the page is generated at this time.

The next step is simple. We will analyze every item in the page lifecycle step by step:

1. Initialization

Initialize the init event and oninit method of the corresponding page.

If you want to rewrite it, the recommended method of msdn is to reload the oninti method, instead of adding an init event proxy. The two are different. The former can control the order of calling the parent class oninit method, the latter can only be executed after the oninit of the parent class (actually called in oninit ).

2. Load view status

This is an important method. We know that each request is actually handled by different page-class instances. To ensure the status of the two requests, Asp. net uses viewstate.

The loadviewstate method obtains the last state from the viewstate and uses recursion to traverse the entire tree based on the control tree structure of the page to restore the corresponding state to each control.

3. process the returned data

This method is used to check whether the status of the control data sent back from the client has changed. Method prototype:

Public Virtual bool loadpostdata (string postdatakey, namevaluecollection postcollection)

Postdatakey is the key that identifies the control (that is, the key in postcollection). postcollection is a set of returned data. We can rewrite this method and check whether the returned data has changed, if yes, a true value is returned. "If the control status changes due to sending back, loadpostdata returns true; otherwise, false is returned. The page framework tracks all controls that return true and calls raisepostdatachangedevent on these controls ." (From msdn)

This method is system. web. webcontrols. the custom control defined in control is also the method for processing all custom controls that need to process events. For the page we are discussing today, you can ignore it.

4. Load

Load the corresponding load event and onload method. I believe most of my friends will be familiar with this event. the page_load method in the page generated by net is the method for responding to the load event. For each request, the load event is triggered and the page_load method is executed. I believe most people know about ASP. net.

The page_load method responds to the load event, which is in the system. web. webcontrol. defined in the control class (this class is the ancestor of page and all server controls), and is triggered in the onload method.

Many people may have encountered such a problem. They wrote a pagebase class and then verified the user information in page_load. The results showed that page_load on the subclass page is always executed no matter whether the verification is successful or not, this may leave some security risks. The user may execute the page_load method in the subclass without being verified.

The reason for this problem is very simple, because the page_load method is added to the load event in oninit, And the oninit method of the subclass adds the load event first, and then calls the base. oninit, which causes the page_load of the subclass to be added first and then executed first.

There are two ways to solve this problem:

1) Reload the onload method in pagebase, verify the user in onload, and then call base. onload, because the load event is triggered in onload, so that we can ensure that the user is verified before the load event is triggered.

2) Call base. oninit in the oninit method of the subclass to ensure that the parent class executes page_load first.

5. Send a change notification

This method corresponds to the process of sending back data in step 1. If the process returns true, the page framework will call this method to trigger the data change event, therefore, the custom control's send-back data change event must be triggered in this method.

Similarly, this method is not very useful for pages. Of course, you can also define data change events based on pages. This is also possible.

6. Handle sending back events

This method is triggered by most server control events. When the request contains the information triggered by the control event (the Server Control event is another topic, and I will discuss it in the near future ), the Page Control calls the raisepostbackevent method of the corresponding control to trigger server events.

A common problem is raised here:

Some netizens often ask why the modified data has not been changed.

In most cases, they do not understand the server event trigger process. We can see that the server event is triggered after the page load, that is, the page will first execute page_load, then the click event will be executed (Here we take the button as an example). Many of my friends bind data in page_load and then process the changes in the button event. There is a problem with this, page_load is always executed before the button event, which means that the data has not been changed. The code bound to the data in page_load is executed first, and the original data is assigned to the control, when the button event is executed, the original data is actually obtained, so the update will of course be ineffective.

It is also very simple to change this issue. A reasonable practice is to write the data binding code as a method. We assume it is binddata:

Private void binddata ()
{
// Bind data
}

Then modify pageload:

Private void page_load (Object sender, eventargs E)
{
If (! Ispostback)
{
Binddata (); // bind data when the page is accessed for the first time
}
}

Finally, in the button event:

Private button#click (Object sender, eventargs E)
{
// Update data
Binddata (); // rebind data
}

7. Pre-presentation

The final request processing will be converted to the response sent back to the server. The pre-presentation phase is to execute the state changes made before the final presentation, because before a control is rendered, we must generate HTML based on its attributes, such as the style attribute. This is the most typical example. Before pre-rendering, we can change the style of a control. When pre-rendering is executed, we can save the style as the HTML style information displayed in the rendering stage.

8. Save status

This phase is for the loading status. We have mentioned many times that different instances are being processed between requests. Therefore, we need to save the status of this page and control, this stage is the stage of writing the state into viewstate.

9. Rendering

Here, in fact, the processing of the page request has basically come to an end. In the render method, the control tree of the entire page will be recursion, And the render method will be called in sequence, write the corresponding HTML code into the final response stream.

10. Disposal

It is actually the dispose method. In this phase, the occupied resources will be released, such as database connections.

11. Uninstall

Finally, the page will execute the onUnload method to trigger the unload event and process the final processing before the Page Object is destroyed. In fact, Asp. NET provides this event only for design considerations. Generally, the release of resources will be completed in the dispose method, so this method also becomes a weakness.

We briefly introduced the page lifecycle and made a little in-depth explanation of server-side event processing. Today, I want to know the page execution cycle, for server control events and lifetime, I will write someArticle.

I am learning ASP. some of my experiences with page research during the course of net, but I have not discussed the details in detail. For more information, please refer to msdn, however, I have cited some common mistakes and the causes of errors for beginners, hoping to inspire you.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.