Application Session Cookie viewstate cache in Asp.net

Source: Internet
Author: User

 

Application

1. The application is used to save information shared by all users.

2. In the ASP era, if the data to be stored does not or rarely change during the lifetime of the application, application is the ideal choice. However, in the Asp.net development environment, we put similar configuration data in Web. config.

3. if you want to use the application, note that all write operations must be completed in the application_onstart event (Global. asax), even though application. lock () avoids conflicts, but serializes application requests, which can cause serious performance bottlenecks.

4. Do not use application to save large data volumes.

5. Code: application ["userid"] = "test ";

String username = application ["userid"]. tostring ();

Session

1. Session is used to save the proprietary information of each user.

2. The session lifetime is the user's sustained request time plus a period of time (generally about 20 minutes)

3. The session information is stored in the web server memory, and the stored data volume can be large or small.

4. Data will be automatically released when the session times out or is disabled.

5. This method is inefficient because it remains in memory for a period of time after the user stops using the application.

6. Code: session ["userid"] = "test ";

String username = session ["userid"]. tostring ();

Cookie

1. Cookie is used to save the request information of the client browser requesting the Server Page

2. We can store non-sensitive user information and set the storage time as needed.

3. If no cookie expiration date is set, its lifecycle is saved until the browser is closed.

4. Setting the expires attribute of the cookie object to minvalue indicates that the object will never expire.

5. The amount of data stored in cookies is limited. Most browsers use 4 K, so do not store magnified data.

6. Because not all browsers support cookies, data will be stored in plaintext on the client.

7. Code: resopnse. Cookies ["userid"] = "test ";

String username = resopnse. Cookies ["userid"]. tostring ();

Viewstate

1. viewstate is used to save the user's status information. The validity period is equal to the lifecycle of the page.

2. You can save a large amount of data, but use it with caution because it will affect program performance.

3. All Web server controls use viewstate to save the status during page PostBack.

4. Disable enableviewstate = false in @ page if not required.

5. Code: viewstate ['"Id"] = "yiner ";
String id = viewstate ["ID"]. tostring ();

Cache

1. cache is used to save pages or data during HTTP requests

2. The use of cache can greatly improve the efficiency of the entire application.

3. It allows you to store frequently accessed server resources in the memory. When the user sends the same request
Instead of processing the data again, the server directly returns the data saved in the cache to the user.

4. We can see that cache saves time-server processing time

5. the cache instance is exclusive to every application, and its lifecycle = This application cycle
Restart the application and re-create its instance

6. Note: To use functions such as cache cleanup, expiration management, and dependency items, you must use the insert or add method to add information.

7. Code: cache ['"Id"] = "yiner"; or cache. insert ("ID", "test ");
String id = cache ["ID"]. tostring ();

Hidden

1. The hidden control is an HTML-type server control and is always hidden.

2. Each time it is submitted, it will be submitted to the server together with other server controls.

3. The Code is as follows: hidden. value = "King ";
String id = hidden. value; Use runat = Server

Usage and differences between ASP. NET application, session, Cookie, viewstate, and other objects

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 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:

(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 + 1, total number of bytes + 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.