ASP.NET Web Page in-depth study

xiaoxiao2021-03-06  54

First, the server script foundation first, let's review the basic execution of the web server page first: 1. The client sends a request to the server side by tapping the address in the browser's address bar. After receiving the request, it is sent. The corresponding server end page (that is, script) is executed, the script generates the client's response, send it back to the client 3, the client browser receives the response of the server, parsing the HTML, rendering the graphic web page in the user before

For the interaction of the server and client, it usually passes 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: pass The parameters of the URL reach the parameters to the server, this method is actually the same as the GET mode 3, cookies: This is a relatively special way, usually used for user identity confirmation

Second, ASP.NET Introduction Traditional server scripting languages, such as ASP, JSP, etc. Similar scripts, the living cycle of the page is actually very simple, that is, from the beginning to the end, execute all the code, of course, servlets written in Java can write more complex code, but from the structure, and JSP has no 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 ASP.NET does not leave the web programming mode, so it is still in request -> reception request -> processing request -> Send a mode in this mode, each The interaction with the client will trigger a new request, so 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 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 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 Creating an instance of the request page class, performing its ProcessRequest method to handle the request, this method is the beginning of the Web Page lifecycle. 4. ASPX page and CodeBehind before we deeply understand the life cycle of the page, let's discuss 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 analyze it: 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 name of the class inheritance, which is the class in the codebehind code file, this class must be from System.Web.WebControls .Page derived from above we can analyze, in fact, classes in CodeBehind are the base class of page (ASPX), here, some friends may ask, when writing ASPX, it is fully based on ASP, in HTML In the middle embedding code 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" File, in fact, this is the result of Asp.Net dynamic compiler, open these source files. We can find: public class webform_aspx: mynamespace.webform, system.web.SessionState.irequiressessionState This confirms our previous statement, ASPX Is the subclass of the code binding class, its name is an ASPX file name plus the "_ASPX" suffix, through research we can find that the server control defined in all ASPX is generated in these code, then When these codes are dynamically generated, 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, the code binding file will always add a declaration: protected system.web.webcontrols.button button1; we can find this field Declare into protected, and the name is consistent with the ID of the control in ASPX, think about it carefully, this problem is unspeakable. 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 generated by the control, which gives the reference to the corresponding variable in the parent class, which is why the parent class The statement must be protected (actually available for public) because the subclass is to 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. 5. The page survival cycle is now returned to the contents of the third title. We talked about the instance of HTTPApplication instance reception request, and creating an instance of the page class. In fact, this instance is an instance of the class that is dynamically compiled aspx, In the previous title, we learned that 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 to start 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. // InitializeComponent (); base.onit (e);} ///

/// Designer supports the required method - Do not use the code editor to modify the // / this method. ///

private void InitializeComponent () {this.DataGrid1.ItemDataBound = new System.Web.UI.WebControls.DataGridItemEventHandler (this.DataGrid1_ItemDataBound); this.Load = new System.EventHandler (this.Page_Load);

} #ENDREGION This is the code generated by VS.NET. Let's see, there are two ways, one is oninit, one is initializeComponent, the latter is called by the former, actually this is the beginning of the page initialization, InitializeComponent we saw the control's event declaration and page's Load declaration. Below is a description from the MSDN and a sequence table for a page lifecycle method and event trigger: "Each time the ASP.NET page is requested, 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 presented HTML to the client. Although communication between clients and servers is stateless and intermittent, it must make customers feel this is a continuous process "This continuous illusion is implemented by the ASP.NET page framework, page and its control. After returning, the active behavior must appear to start from the last web request. Although ASP.NET Page The framework can make the execution state management is relatively easy, but in order to obtain continuity, the control developer must know the execution order of the control. The control developer needs to know: What information can be used in the control life cycle, which data can be used Which state is present when the control 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 life cycle. For more information, please click on the table Link. "Due to the topic of the typography, I will be hereained here. For example, please refer to: ms-help: //ms.vscc/ms.msdnvs.2052/cpguide/html/cpcontrulexecutionLifeCycle.htm> Initialization LoadViewState method processing Return data loadPostData method Load LOAD event Send a return change Notification RaisePostDataChangeDevent method Processing Raise RaisePostBackevent Method Pre-presentation prerender event Save Status SaveViewState method Render method to deal with Dispose method Uninstall 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, let's gradually analyze each item of the page lifecycle: 1. Initialize the initialization of the INIT event and the OnInit method of the corresponding 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, loaded 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 of the request, ASP.NET uses ViewState, about ViewState's description, please refer to another article: http://www.9cbs.net/develop/read_article.asp?id=17686 LoadViewState method is to get the last state from ViewState and follow the control tree The structure is returned to the entire tree with the return, and the corresponding state is restored to each control. 3. Processing the return data This method is to check whether the status of the control data sent back from the client has changed. Prototype: Public Virtual Bool LoadPostData (String PostDataKey, NameValueCollection) PostDataKey is a keyword identified control (the key in PostCollection). PostCollection is a collection of retrace data, we can override this method, then check back Whether the data has changed, if it returns a TRUE, "If the control status changes due to the return, loadPostData returns true; otherwise returns false. Term Framework All Return True and call RaisePostDataChangeDevent on these controls. "(Excerpt 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 the load corresponding to the LOAD event and the online method, for this event, I believe that most friends will be more familiar, 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 The Page_Load method 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) Overload the online 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 Verify the user before triggering the Load event. 2) Call BASE.ONIT first in the onInit method of the subclass, so that the parent class will execute Page_Load 5 first, send a return change to notify this method, corresponding to the process of posting the process, if the process returns True, The page framework calls this method to trigger the event of data changes, so the reputation of the custom control is triggered 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. This method of processing a return event is where most server control events are ranging. When the information is included in the request (the event of the server control is another topic, I will discuss the discussion in the near future), page controls The RaisePostBackeVent method of the corresponding control will call the server-side events. Here, there is a common problem: often asked, why do you have to change the data after the submission is not changed, and the triggered flow of the server event is not understood. We can see that the trigger server event is after Page Load That is to say, the page will execute Page_Load first, then execute the button (here as an example) click event, many friends bind data in Page_Load, then handle 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 the code binded by the data in Page_Load is executed first. The original data is assigned to the control, then the execution button event is executed, In fact, the original data is obtained, then the update is of course no effect.

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

New Post(0)