[C #. Net] ASP. NET status management application, session, cookie, and viewstat usage

Source: Internet
Author: User

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

 

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 application life 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 application_on.Start 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:

(Store 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;

/// 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) // when the current user exits the website, the number of online users-1,

{

Application. Lock ();

Application ["currentguests"] = (INT) application ["currentguests"]-1; // 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 is used to save the dedicated 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. the code for saving information using the session object is as follows:

// Store information

Session ["key"] = "value"

// Read 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 information

Response. Cookies ["key"]. value = "value ";

// Read information

String userid = response. Cookies ["key"]. value;

4. viewstate object

Viewstate is often used to save the status information of a single user, and 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.

// Store information

Cache ["nameid"] = "0001 ";

// Store information

Cache. insert ("nameid", "0001" 1 );

// Read information

String nameid = cache ["nameid"]. tostring ();

6. Hide the 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 information

Hidden. value = "0001 ";

// Obtain information

String nameid = hidden. value;

7. query strings

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"];

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.