ASP. NET status management application, session, cookie, and viewstat usage

Source: Internet
Author: User
In ASP. NET, there are many built-in objects for saving information, such as application, session, Cookie, viewstate and cache. The following describes their usage and differences.
Method Information size Scope and storage time Application Scope Save location
Application Any size Entire ApplicationProgramLife Cycle Entire application/All Users Server
Cache Any size Can be set as needed Entire application/All Users Server
Session Small amount, simple data User Activity time + a delay (generally 20 minutes) Single User Server
Cookie Small amount, simple data Can be set as needed Single User Client
Viewstate Small amount, simple data Life cycle of a web page Single User Client
Hide domain Small amount, simple data Life cycle of a web page Single User Client
Query string Small amount, simple data Until the next page Jump request Single User Client
1. Application Object Application is used to save the public data information of all users. If the application object is used, a problem to be considered is that any write operation must be performed on the application_onstart event (Global. asax. although application. lock and applicaiton. the unlock method is used to avoid synchronization of write operations. However, it serializes the requests to the application object. When the site traffic is large, it will produce a serious performance bottleneck. therefore, it is best not to use this object to store large data sets. the following is an example of online user statistics to illustrate this problem: (storing the total website traffic in the form of files) Global. asax class Using System; using System. collections; using System. componentmodel; using System. Web; using System. Web. sessionstate; using System. IO; // a summary of Global. Public class Global: system. Web. httpapplication {// required designer variables. Private system. componentmodel. icontainer components = NULL ;
Private Filestream; private streamreader reader; // read the volume stream Private streamwriter writer; // write the volume stream. Public Global () {initializecomponent ();}
Protected void Application_start (Object sender, eventargs e) {application ["currentguests"] = 0; // The initial spending is 0; Filestream = file. Open (server. mappath ("counts. Text"), filemode. openorcreate); // the file does not exist. Create a file Reader = new streamreader (filestream); // complete path to be read Application ["allguests"] = convert. toint32 (reader. Readline (); // read a line of characters from the current stream and return the data as a string Reader. Close (); // close the stream }
Protected void session_start (Object sender, eventargs e) // when a user accesses a website, the number of online users is + 1, and the total number of visits is + 1. {Application. Lock (); // synchronous to avoid simultaneous write Application ["currentguests"] = (INT) application ["currentguests"] + 1; // total number of online users Application ["allguests"] = (INT) application ["allguests"] + 1; // total number of users accessing the website Filestream = new filestream (server. mappath ("counts. Text"), filemode. openorcreate, fileaccess. readwrite ); // Writer = new streamwriter (filestream); // implements a write stream so that it writes characters to the stream in a specific encoding. Writer. writeline (application ["allguests"]. tostring (); // write the total number of users accessing the website to the file again Writer. Close (); // close the write stream.
Application. Unlock (); // Synchronization ends } Protected void session_end (Object sender, eventargs e) // number of online users when the current user exits the website -1, {Application. Lock (); application ["currentguests"] = (INT) application ["currentguests"]-1; // The total number of online users -1 Application. Unlock ();} (2) webform1.aspx private void page_load (Object Sender, system. eventargs e) {This. label1.text = "Number of users accessing the site: "+ Application [" currentguests "]. tostring (); this. label2.text =" Total number of users who have accessed the site: "+ Application [" allguests "]. tostring ();} 2. Session Object Session Used to save the private information of each user . During access by each client user, the server assigns a unique session ID (session ID) to each user ). her survival time is the user's continuous request time plus a period of time (usually about 20 minutes ). the session information is stored in the web server content. The stored data volume can be large or small. the stored data is automatically released when the session times out or is disabled. because the user stops using the application and it remains in the memory for a period of time, the session object is used to save user data very efficiently. for a small amount of data, it is a good choice to use the session object to save. when the session object is used to save information Code As follows: // stores information session ["key"] = "value" // reads data string username = session ["key"]. tostring (); 3. Cookie Object Cookie is used to save the request information of the client browser request Server Page. programmers can also use it to store non-sensitive user information. The time for saving the information can be set as needed. if no cookie expiration date is set, they are only saved until the browser program is closed. if the expires attribute of the cookie object is set to minvalue, the cookie will never expire. the amount of data stored in cookies is very limited. Most browsers support a maximum capacity of 4 K. Therefore, it is not used to save datasets and other large amounts of data. since not all browsers support cookies and data information is stored in plain text on the client's computer, it is best not to store sensitive, unencrypted data, otherwise, the website security will be affected. the code for saving the cookie object is as follows: // store the information response. cookies ["key"]. value = "value"; // read information string userid = response. cookies ["key"]. value; 4. viewstate Object Viewstate It is often used to save the status information of a single user. The validity period is equal to the lifetime of the page. Similar to hidden controls. Viewstate is used to pass values between functions on this page. As to why this method is used, the page may be refreshed after an event occurs. If global variables are defined, therefore, viewstate is used. the viewstate container can maintain a large amount of data, but it must be used with caution because excessive use may affect the application performance. All Web server controls use viewstate to save their status information in the page sending and playback period. If a control does not need to save the status information during sending back, it is best to disable the viewstate of the object to avoid unnecessary resource waste. You can disable the viewstate of the entire page by adding the "enableviewstate = false" attribute to the @ page command. The code for saving information using the viewstate object is as follows. // Store information viewstate ["key"] = "value"; // read information string nameid = viewstate ["nameid"]. tostring (); 5. Cache Object Cache objects are used to save pages or data between HTTP requests. This object can greatly improve the efficiency of the entire application. It is often used to store a large number of frequently accessed server resources in the memory. When a user sends the same request, the server returns the information stored in the cache to the user instead of processing it again, this reduces the time required for the server to process requests. The lifetime of the application depends on the lifetime of the application. When the application is restarted, the instance of its cache object is re-created. The code for saving information using a cache object is as follows. // Save information cache ["nameid"] = "0001"; // store information cache. insert ("nameid", "0001" 1); // read information string nameid = cache ["nameid"]. tostring (); 6. Hide domain The hidden control is a server control of the HTML type. You can use this control to hide fields. In fact, this control is no different from other server controls, but it is not displayed in the browser of the user end and is always hidden. However, this control is submitted to the server together with other server controls each time the page is submitted. Therefore, the server can use the value attribute to obtain or save some data information. The following code uses the hidden control to save information. // Store the information hidden. value = "0001"; // obtain the information string nameid = hidden. value; 7. Query string To query a string, connect the value to be passed to the URL and use the response. Redirect method to redirect the client. In this way, information can be transmitted between two pages. Because the length of the URL is limited, too much information cannot be transmitted, and the security of the URL is not very good. The transfer information is as follows. Format key1 = value1 & key2 = value2 Response. Redirect ("list. aspx? Nameid = 0001 & gradeid = 002 "); // the code of the URL displayed in the IE Address Bar after executing the preceding statement is as follows. Http: // localhost/list. aspx? Nameid = 0001 & grade = 002 // After you jump to list. aspx, you can use the following code to obtain the transmitted information. String Nameid. gradeid; nameid = request. Params ["nameid"]; gradeid = request. Params ["gradeid"]; Source: Pashine blog

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.