ASP. NET status management details to make it clear

Source: Internet
Author: User

Programmers who develop WinFrom may not care about maintaining the application state, because WinFrom itself runs on the client and can directly maintain the application state in the memory. However, ASP.. NET applications run on the server, and the client uses the stateless http protocol for ASP. NET application sends a request, ASP.. NET Applications respond to user requests and send the requested HTML code to the client. The server does not maintain any client status. Consider a server with thousands of concurrent users. If you maintain the status for each user, it will consume a lot of resources.

 

Because stateless http is used as the communication protocol for web applications, each time the client requests a page, the ASP. NET Server will generate a new web page instance. This means that the client user's status in the browser or some modifications will be lost.

Remember that when using ASP, a large number of Session variables are used to save the values of each text box before data submission to save the values of each text box, after the page is regenerated, the values in these session variables are assigned to each text box. This is a very time-consuming and laborious task.

ASP. NET provides the State management technology. The state technology automatically saves and assigns the status of each control. In addition, it provides a control state technology.

ViewState: one or more hidden fields are used to save control data.

Of course, we can also use it to save our own State data by using the built-in object ViewState [key] = value ;. This object is of the dictionary type. Type conversion is required when the value is to be obtained. int I = (int) ViewState [key], because the storage type of the value in ViewState is Object. The data stored in ViewState can be simple or custom, however, custom types must support serialization (that is, when declaring a class, you must write the [Serializable] level on the class ). However, it should be clear that ViewState is used to save data only on the current page of the current user, and information cannot be transferred across pages. Because it can save the status of most controls by default, it will occupy a large amount of network bandwidth when transferring back and forth between the server and the client, and because it is stored on the client, therefore, it will occupy too much client memory and thus affect the execution efficiency. Therefore, for some controls that do not need to save the state in ViewState, we can disable the view State through its EnableViewState attribute. You can also disable all view states on the Page by <% @ Page EnableViewState = "false">. The view status is through ASP. the NET engine saves it in a hidden domain HiddenField, <input type = "hidden" name = "_ VIEWSTATE" id = "_ VIEWSTATE" value = "These statuses are saved as key/value pairs and encoded in Base64 format" >. Because Base64 encoded strings can be decoded by many tools (such as ViewStateDecoder), it is dangerous to store sensitive data in the view State. If you want to store sensitive information in the view state, you can

ViewStateEncryptionMode = "Always"> or set the value of ViewStateEncryptionMode in the pages node of Webconfig. You can also go to Page. RegisterRequiresViewStateEncryption () in the post code, provided that the ViewStateEncryptionMode is not set to Never in the @ Page and pages nodes. In this case, a hidden domain name is _ VIEWSTATEENCRYPTED.

 

ControlState: When a custom control is developed, the control state data is saved.

To make the control work normally, you sometimes need to store the control status data. For example, if you write a custom control with different tabs that display different information, to make the control work as expected, the control needs to know which tab is selected during the round-trip process. The ViewState attribute can be used for this purpose, but developers may disable the view State at the page level to effectively interrupt the control. To solve this problem, the ASP. NET page framework discloses a new function called control state in ASP. NET 2.0. The ControlState attribute allows the control-Specific Property Information to be kept, unlike the ViewState attribute. To use the control status, the control must call the RegisterRequiresControlState method during initialization, And Then override the SaveControlState and LoadControlState methods.

 

By default, the ASP. NET page framework stores the control status in a hidden element of the page, and the view status is also stored in this hidden element. Even if the view status is disabled or the Session management status is used, the control status on the page is still transmitted to the client and then returned to the server. When sending a response, ASP. NET deserializes the content of the hidden elements and loads the control status to each control that has registered the control status.

 

According to a series of technical references on MSDN, ControlState should be mainly used on custom controls. the NET page framework provides the ControlState attribute as a method for storing custom control data during server round-trip. "This is the original sentence on MSDN, ASP. NET2.0 only provides a foundation for ControlState. When ControlState is a custom state persistence mechanism, that is to say, the State persistence mechanism needs to be completed by your developers, rather than ViewState, it has its own default status persistence mechanism. The use of ControlState in a custom control may be Microsoft's intention, so as to avoid the normal operation of the custom control after ViewState is disabled at the page level. Of course, this means that the correct running of some controls depends on its status information. In ASP. NET1.1, if ViewState is disabled, the controls cannot run correctly. However, ControlState is different after it is introduced, because ControlState cannot be disabled.

So Microsoft reminded developers that "Please use the control status only for a small amount of key data that is critical to the control during the sending-back process, instead of using the control status as an alternative option for view status ". Clearly, ControlState and ViewState are two things. Although they can accomplish the same task, the new ControlState is neither used to replace ViewState nor to replace ViewState. Its mission is to make up for the tasks that cannot be completed by ViewState, so that developers can develop more robust controls. For example, a State of a developed custom control is crucial. Without it, the custom control cannot work normally, so the ControlState should be on the stage. In addition, ControlState is a custom state persistence mechanism that limits the use of ControlState. You should not only register the OnInit method and call the RegisterRequiresControlState Method to the page, but also rewrite SaveAdapterControlState (), the LoadAdapterControlState (object state) method implements what to save and how to save it. According to my understanding, if you need to save 10 different states of the control, you have to save them one by one and load them one by one. From this point, we can see the original intention of Microsoft. Isn't that obvious? If you don't need ControlState, don't use it. Otherwise, how can we let our developers do everything?

 

Link: http://kendezhu.iteye.com/blog/810562's 3 and 5

Http://www.cnblogs.com/think-jerry/archive/2007/05/24/753660.htmland its next article

 

Cookie session application

 

Session

Session is similar to ViewState. It can also save any standard data type and any object derived from the object type. However, the Session can be saved across pages. When a user jumps to another page without changing the browser, the user can still get the data saved on the previous page through the Session. The Session status is different from the ViewState, which is stored on the server side. ASP. NET will create a unique SessionID (120-bit identifier) for each Session. This SessionID will be sent to the client as a Cookie or Url, in this way, the server can maintain the Session of each client according to the SessionID of the client (no matter whether the Session ["key"] = is used in the program or not, the Session is established on the server, sessionID will be sent to the client, but the session is established, and the SessionID will be useful and can be used to maintain the session of each client ). However, when the client user closes the browser and uses different browsers, the server session status will be lost if no operation is performed for a long time, resulting in Session Timeout. The session status is stored in the server's memory by default. This is certainly an efficient advantage, but it will occupy a large amount of server-side memory. We can save it to the database and other places, the following describes how to configure the session Status in webconfig:

Add the sessionState node to the system. web node of webconfig as follows:

<System. web>

<SessionState

Cookieless = "UseCookies" cookieName = "ASP. NET_sessionid"

Mode = "SQLServer" timeout = "20"

SqlConnectionString = "Data Source =. \ sqlexpress; Integrated Security = SSPI"

SqlCommandTimeout = "30">

</SessionState>

</System. web>

Cookieless sets whether SessionID is sent to the client using a Cookie or Url, or is determined by detection. CookieName sets the name of the Cookie that saves SessionID. Mode: sets the Session state saving mode. By default, InProc is saved in the server memory. Here, it is set to be saved in the SQLServer database. SqlConnectionString sets the connection string. SqlCommandTimeout sets the timeout value.

After setting, enter:

Aspnet_regsql.exe-S. \ SQLEXPRESS-E-ssadd-S is followed by the database server name

A database ASPState is added to the server. To remove the database, enter:

Aspnet_regsql.exe-S. \ SQLEXPRESS-E-ssremove

However, the status table is in the tempdb database, so restarting SQLServer will cause session information loss. Enter:

Aspnet_regsql.exe-S. \ SQLEXPRESS-E-ssadd-sstype p

In this way, the status table will appear in the ASPState database and the session information will be permanently retained.

If you want to save the status data in your own database, enter:

Aspnet_regsql.exe-S. \ SQLEXPRESS-E-ssadd-sstype c-d Database Name

Then modify the attributes in the sessionState node:

AllowCustomSqlDatabase = "true" allows the use of custom Databases

SqlConnectionString = "Data Source =. \ sqlexpress; Initial Catalog = tempdb; Integrated Security = SSPI" link string and database

Related links:

Http://www.cnblogs.com/shoru/archive/2010/02/19/1669395.html

Http://www.cnblogs.com/flier/archive/2004/08/04/30226.html (1)

Http://www.cnblogs.com/flier/archive/2004/08/07/30902.html (2)

 

Application

The Application is used in the same way as the Session and stored on the server. However, Application is a global object, which is not only limited to a page or a browser, but is shared by all users. Besides, it does not have timeout unless the server is shut down or restarted. The most common example is the Web page counter:

 

Protected void Page_Load (object sender, EventArgs e) {int I = 0; if (Application ["PageCount"]! = Null) {Application. lock (); Lock to prevent multiple users from simultaneously accessing (concurrent access) I = (int) Application ["PageCount"]; I ++; Application ["PageCount"] = I; application. unLock (); UnLock after operation} else {Application ["PageCount"] = 0;} Label1.Text = I. toString ();}

 

 

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.