ASP. NET in-depth introduction to series 1-asp.net programming models

Source: Internet
Author: User

I. http protocol:
1. What is HTTP?
The website address we enter in the address bar of the browser is called URL (uniformresourcelocator, unified Resource Locator ). Just as each household has a home address, each webpage also has an Internet address. When you enter a URL in the browser address box or click a hyperlink, the URL determines the address to be viewed. The browser uses Hypertext Transfer Protocol (HTTP)CodeExtracted and translated into beautiful web pages. Therefore, before we understand HTTP, it is necessary to clarify the URL composition, for example, http://www.microsoft.com/china/index.htm. Its meaning is as follows:

    • Http: //: Indicates Hypertext Transfer Protocol. A web page is displayed on the Microsoft.com server, which is usually not input;
    • Www: represents a web (World Wide Web) server;
    • Microsoft.com/:the Domain Name of the server with web pages or the name of the site server;
    • China/: The subdirectory on the server, just like our folder;
    • Index.htm: index.htm is an HTML file (webpage) in the folder ).

We know that the basic protocol of the Internet is the TCP/IP protocol. However, the top layer of the TCP/IP model is the application layer, which contains all high-level protocols. High-level protocols include file transfer protocol FTP, email transmission protocol SMTP, Domain Name System Service DNS, network news transmission protocol NNTP and HTTP. Hypertext Transfer Protocol (Hyper Text Transfer Protocol) is a transfer protocol used to transfer hypertext from a WWW server to a local browser. It makes the browser more efficient and reduces network transmission. It not only ensures that the computer transfers hypertext documents correctly and quickly, but also determines which part of the transmitted documents and which part of the content is first displayed (such as text before graphics. This is why all the web addresses you see in your browser start with "http.
2. How HTTP works
Because the HTTP protocol is based on the request/response paradigm (equivalent to the Client/Server ). After a client establishes a connection with the server, it sends a request to the server in the format of Uniform Resource Identifier (URL), Protocol version number, the mime information is followed by the request modifier, client information, and possible content. After receiving the request, the server sends a response in the format of a status line, including the Protocol version number of the message, a successful or wrong code, mime information is followed by server information, entity information, and possible content.

Many HTTP communications are initiated by a user proxy and include a request to request resources on the source server. The simplest case may be that a separate connection is established between the user proxy and the server. On the Internet, HTTP Communication usually occurs over TCP/IP connections. The default port is tcp80, but other ports are also available. However, this does not indicate that the HTTP protocol can be completed over the Internet or other network protocols. HTTP only indicates a reliable transmission.

In WWW, "customer" is a relative concept with "server". It only exists in a specific connection period, that is, the customer in a connection may act as a server in another connection. The HTTP-based Client/Server mode information exchange process consists of four processes: establishing a connection, sending request information, sending response information, and closing a connection.

 

In fact, simply put, in addition to HTML files, any server also has an HTTP resident.ProgramTo respond to user requests. Your browser is an HTTP client and sends a request to the server. When a starting file is entered in the browser or a hyperlink is clicked, the browser sends an HTTP request to the server, this request is sent to the URL specified by the IP address. The resident program receives the request and sends the requested file back after necessary operations. In this process, the data sent and received on the network has been divided into one or more packages, each of which includes: data to be transmitted; control information, it tells the network how to process data packets. TCP/IP determines the format of each data packet. If you don't tell you in advance, you may not know that the information is divided into many small pieces for transmission and re-combination.

That is to say, in addition to commodities, a seller also has an employee answering your call. When you call, your voice is converted into various complicated data, when the telephone lines are transmitted to the other party's phone, the other party's phone converts various complicated data into sound, so that the staff of the other party's seller can understand your request. In this process, you do not need to understand how sound is converted into complex data.

3. http protocol analysis under ASP. NET
HTTP Request
First create An ASPX page drag up only one button and a text box, open fiddler (this is a Microsoft employee developed HTTP debugging tool, http://www.fiddlertool.com/), and then browse the page just created. View Fiddler. We will see:

The content in the above box is actually the content submitted to the server by the browser after you press enter, and the server obtains the information and parses it, then, we will provide you with the corresponding page based on your request. Let's briefly introduce the content here:

    • Get: it follows the location of a webpage. The server accepts the request and returns the requested page. In addition to the page location as a parameter, the request can also follow the protocol version such as HTTP/1.0 as a parameter to send more information to the server.
    • Accept-language: Current browser Language
    • HOST: specifies the intenet host and port number of the requested resource, which must represent the location of the original server or gateway of the request URL. The HTTP/1.1 request must contain the Host Header domain; otherwise, the system returns the status code 400.
    • User-Agent: contains the user information of the request, which identifies the browser type of the request.
    • Connection: close a connection or keep a connection valid.

HTTP Response

A server response includes a status line that consists of the Protocol version of the message and an exit code (indicating success or error. The status line is followed by several headers (usually the content type and length of the page) and the body content. An empty line separates the topic content from the rest of the message. For example, the response content of the page just accessed:

 

A server response includes a status line that consists of the Protocol version of the message and an exit code (indicating success or error. The status line is followed by several headers (usually the content type and length of the page) and the body content. An empty line separates the topic content from the rest of the message. For example, the response content of the page just accessed:

Code 200 in the first line indicates that the request is normal. The content of the server is the server information. Content-Type indicates the media type of the object to the receiver, and specifies the object media type sent by the Head Method to the receiver, the text format is UTF-8 encoded.

Ii. ASP. NET page Structure

The ASP. NET page consists of three parts: Page commands, code, and page layout.
Page command: The page command establishes the running environment of the page and specifies how the HTTP Runtime library handles the page
Code: A handler that contains page and control events. If we hide the code, it will not appear.
Page Layout: The page layout indicates that the page framework includes server controls, text, and HTML tags.
Example:

Page example
<% @ Page Language = " C # "   %> <! -- Page commands -->

< Script runat = " Server " > <! -- Code -->
Void Button#click (Object sender, eventargs E)
{
Label1.text
=   " Clicked "   + Datetime. Now. tostring ();
}
</ Script >

< Html > <! -- Page Layout -->
< Head >
< Title > Single - File Page Model </ Title >
</ Head >
< Body >
< Form runat = " Server " >
< Div >
< ASP: Label ID = " Label1 "  
Runat
= " Server " Text = " Label " >
</ ASP: Label >
< BR />
< ASP: button ID = " Button1 "  
Runat
= " Server "  
Onclick
= " Button#click "  
Text
= " Button " >
</ ASP: button >
</ Div >
</ Form >
</ Body >
</ Html >

 

3. ASP. NET page Lifecycle

When an ASP. NET page is running, this page goes through a lifecycle, and a series of processing steps are performed in the lifecycle. These steps include initializing, instantiating controls, restoring and maintaining status, running event handler code, and rendering. Understanding the lifecycle of a page is very important, so that you can write code at the appropriate lifecycle stage to achieve the expected results. In addition, if a custom control is developed, you must be familiar with the page lifecycle to correctly initialize the control, use view status data to fill the control attributes, and run the behavior logic of all controls.

1. object initialization init event: the identifier of page Initialization is the init event. Controls in the page (including the page itself) are initialized for the first time in their initial form. After the control tree of the page is successfully created, this event is triggered for the application. When an init event occurs, all controls declared statically in the. aspx source file are instantiated and Their default values are obtained. It should be noted that there is no view status information available for use. Although the oninit method can be reloaded, the system does not guarantee the order in which these control instances are created.

2. Load view: After initialization, the page framework immediately loads the view status (viewstate) of the page ). The view status is a set of name/value pairs. For example, you can save the ID and text attribute values of the Textbox Control. It is generally used to store information to the server during a round trip, that is, to participate in HTTP requests and responses.

The page view status is stored in the <input type = "hidden"> Field and recorded as the value of _ viewstae. The view status is automatically maintained by ASP. ne. By Rewriting the loadviewstate component, developers can control how to restore the view state and how to film its content to the internal state. 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 send-back data: The view status is restored, and the status of each control of the page tree is the same as that of the control when the browser last presented the page. Next, update the status of these controls to send them to the client.
In the sending and processing phase, each control has the opportunity to update its status so as to accurately reflect the status of corresponding HTML elements on the client. For example, the HTML element corresponding to a server Textbox Control is <input type = text>. In the data sending and returning stage, the Textbox Control retrieves the current value marked by <input> and uses it to refresh its internal status. Each control extracts the corresponding values from the data to be sent and updates some of its attributes. The Textbox Control updates the text property, while the checkbox control refreshes its checked property. The matching relationship between the Server Control and HTML elements is determined by the IDs of the two.

The page framework implements the ipostbackdatahandler interface on each data submission control, and then stimulates the loadpostdata event. Through page parsing, it is found that the ipostbackdatahandle interface control is implemented, in this way, the control status can be correctly returned. When identifying a control, ASP. NET updates the correct control by matching the unique identifier of the Control. This identifier has a name value pair in the name value set and. This is one of the reasons that each control requires a unique identifier in all specific pages. Other steps are completed by the framework, such as determining whether each identifier is unique in the environment and the basic attributes of the control.

The lostpostdata method is prototype as follows:

Public Virtual bool loadpostdata (string postdatakey, namevaluecollection postcollection)

Postdatakey is the key word used to identify the control. It can be understood as the control ID. postcollection is a set that contains the returned data and can be understood as the view status value. This method returns a bool value. If it is true, the status of the control is changed due to sending back; otherwise, false is returned. The page framework will track all controls that return true and call the raisepostdatachangeevent event on these controls.

The loadpostdata method is composed of system .. web. webcontrols. control defined, and each added server control is also from the system .. web. webcontrols. control, so data sending and receiving does not require intervention.

4. Load the page: When the sending and processing ends, all controls on the page are updated based on the changes entered on the client. In this case, the onload event is triggered on the page. I believe most of my friends will be familiar with this event, using Visual Studio. 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. You can use this method to perform page initialization, such as preparing database connection strings. In event reference, to improve performance, the ispostback attribute of the page class is usually used to determine whether data is sent back.

5. Send a change notification to raisepostdatachanged. As described in (3), after all controls that implement the ipostbackdatahandler interface are correctly updated, each control has a Boolean identifier, indicates whether the data of the Control modified after the last submission is changed or its value is maintained. ASP. NET then searches for the changed identifier of any display control data through the search page and fires raisepostdatachanged. The raisepostdatachanged event is triggered only when all controls are updated after the load event occurs. This ensures that the data of other controls is not manually changed in the raisepostdatachanged event before the control is updated. Although you can also define data change events based on the page, this event is usually of great use.

6. process the send-back event. raisepostbackevent: After a server event is triggered due to a data change caused by a callback update, the objects that are returned will be processed in the raisepostbackevent event. This type of backhaul object is usually a control that is triggered when a button is clicked or its status changes. For example, the button triggers the happy onclick event, the client modifies the text of a text box, sets autopostback to true, and triggers the textchanged event.

A lot of code is executed in this event, because this is an ideal place to control the event-driven logic. To ensure the correctness of the data presented to the browser, the raisepostbackevent event is finally triggered after a series of return events. Based on consistency considerations, the changed control will be passed in until the function is updated after execution. In the actual ASP. NET development work, the task is to pre-process the code before this event occurs.

7. Pre-rendering prerender: After processing the re-sending event, the page is ready for rendering. This phase marks the prerender event. Each control can take advantage of this opportunity to perform any last update operation that needs to be completed before the view State is saved and the output result is displayed. The final request processing will change to the server's response. The pre-presentation phase is to execute the state changes made before the final presentation, because before a control is rendered, HTML must be generated based on its attributes, such as the style attribute. This is a typical example. Before pre-rendering, you can change the style of a control. When pre-rendering is executed, you can save the style as the HTML style information displayed in the rendering phase.

8. Save state saveviewstate: the next state is saveviewstate. in this state, all controls and the page itself can refresh the content of their own savestate set. The view State is subsequently serialized, hashed, base64 encoded, and associated with the VI-EMSTATE to hide the self-end.

9. Rendering view render: Here, in fact, the processing of the page request has basically come to an end. In the render event, the called objects are also rendered as HTML, then, HTML is collected and sent to the customer. After receiving the HTML Tag, the customer reorganized the tag and displayed it to the customer. When a render event is reloaded, the developer can create a fixed-value HTML for the browser. At this time, any HTML created on the page has not yet taken effect. The render method uses the htmltextwriter object as a parameter and generates HTML for the browser. This is mainly used for the development of custom controls.

10. Dispose of disposed: Execute all final cleanup operations before the control is destroyed. In this phase, reference to expensive resources must be released, such as memory exit and database connection.

11. Unload: The final survival mark of a page is the unload event, which occurs before the Page Object is removed. In this event, you can call the dispose method to release any key resources (such as files, graphical objects, and database connections) that are used as much as possible ).

 

References:

Http://www.cnblogs.com/framework/archive/2006/10/16/529835.html

Http://www.fiddlertool.com

Http://www.cnpaf.net/class/http/

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.