Object usages and differences (RPM) for ASP. Application,session,cookie and ViewState

Source: Internet
Author: User

In ASP., there are many built-in objects for storing information, such as: Application,session,cookie,viewstate and Cache. The following describes their usage and differences, respectively.

Method

Information size

Scope and save time

Application scope

Save location

Application

Any size

Lifetime of the entire application

Entire application/All users

Server-side

Cache

Any size

Can be set as required

Entire application/All users

Server-side

Session

Small, simple data

User activity time + a delay time (typically 20 minutes)

Individual users

Server-side

Cookies

Small, simple data

Can be set as required

Individual users

Client

Viewstate

Small, simple data

The lifetime of a Web page

Individual users

Client

Hidden fields

Small, simple data

The lifetime of a Web page

Individual users

Client

Query string

Small, simple data

Until the next page jump request

Individual users

Client


1.Application
Objects

Application is used to hold public data information for all users, and if you use application objects, one of the issues to consider is that any write operations are in the Application_OnStart event (Global.asax) is completed. Although the Application.Lock and Applicaiton.unlock methods are used to avoid synchronization of the write operation, it has serialized the request for the Application object. Serious performance bottlenecks occur when the site is heavily visited. It is therefore best not to save large data collections with this object. Let's do an online user statistics example to illustrate the problem:
(Total number of site visits as a file)

Global.asax class

usingSystem;
UsingSystem.Collections;
UsingSystem.ComponentModel;
Usingsystem.web;
UsingSystem.Web.SessionState;
UsingSystem.IO;
Summary description of Global.
 Public classGlobal:System.Web.HttpApplication
{
The required designer variables.
private System.ComponentModel.IContainer components = null;

PrivateFileStream FileStream;
Private StreamReader reader;//Read character stream
Private StreamWriter writer;//write character stream

PublicGlobal ()
{
InitializeComponent ();
}

protected voidApplication_Start (Object sender, EventArgs e)
{
application["currentguests"]=0;//initial flower is 0;
FileStream = File.Open (Server.MapPath ("Counts.text"), filemode.openorcreate);//file does not exist, create file
reader = new StreamReader (fileStream);//The full path to read
application["allguests"] = Convert.ToInt32 (reader. ReadLine ()); Reads a line of characters from the current stream and returns the data as a string
Reader. Close ();//Closed stream
}

protected void Session_Start (Object sender, EventArgs e)//When users visit the site, online users +1, total visits +1
        {
Application.Lock ();//Synchronize to avoid simultaneous writing

application["currentguests"] = (int) application["currentguests"]+ 1;//total number of online users
application["allguests"] = (int) application["allguests"]+ 1;//total number of users visiting the site
FileStream = new FileStream (Server.MapPath ("Counts.text"), filemode.openorcreate,fileaccess.readwrite); //
writer = new StreamWriter (fileStream);//implement 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 who visit the site again to the file
writer. Close ();//Shutdown Write stream

Application.UnLock ();//Sync End
        }
protected void Session_End (Object sender, EventArgs e)//number of online users when the current user exits the site-1,
{
Application.Lock ();
application["currentguests"] = (int) application["currentguests"]-1;//total number of online users-1
Application.UnLock ();
}
(2) WebForm1.aspx
private void Page_Load (objectsender, System.EventArgs e)
{
This. Label1.Text = "Number of users who are accessing the site:"+ application[" currentguests "]. ToString ();
This. Label2.Text = "Total number of users who have visited the site:"+ application[" allguests "]. ToString ();
}

2.Session Object
Session used to save private information for each user . When each client user accesses, the server assigns a unique session ID to each user (the session ID). Her lifetime is the user's persistent request time plus a period of time (typically 20 minutes or so). The information in the session is saved in the Web server content, and the amount of data saved can be large or small. The saved data information is automatically freed when the session expires or is closed. Because the user stops using the application, it remains in memory for a period of time, Therefore, using the session object makes it very inefficient to save user data. For small amounts of data, it is a good idea to use session objects to save. The code for saving information using the Session object is as follows:

Store information
session["Key"]= "value"
Reading data
String username=session["key"]. ToString ();

3.Cookie Object
Cookies are used to store request information from a client's browser requesting a server page, and the programmer can use it to store non-sensitive user information, which can be set as needed. If the cookie expiration date is not set, They are only saved until the browser program is closed. If you set the Expires property of a cookie object to MinValue, the cookie will never expire. Cookies are limited in the amount of data stored, and most browsers support a maximum capacity of 4K. So don't use it to save datasets and lots of other data. Because not all browsers support cookies, and the data information is stored in clear text in the client computer, it is best not to save sensitive, unencrypted data, Doing so will affect the security of your site. The code saved with the cookie object is as follows:

Store information
response.cookies["Key"]. Value= "Value";
Reading information
String userid=response.cookies["key"]. Value;

4.ViewState Object
ViewState often used to hold the status information for a single user, which is equal to the lifetime of the page. Similar to hidden controls. ViewState is the value of each function in this page, as to why to use this method is because after an event occurs, the page may be refreshed, if the definition of global variables will be zeroed, so use viewstate. ViewState containers can maintain large amounts of data, but must be used with caution, because excessive use can affect the performance of the application. All Web server controls use ViewState to save their state information in a page postback tone. If a control does not need to save state information during a postback, it is a good idea to close the object's viewstate to avoid unnecessary waste of resources. You can suppress the viewstate of the entire page by adding the "Enableviewstate=false" property to the @page directive. The code for saving information using the ViewState object is as follows.

Store information
viewstate["Key"]= "value";
Reading information
String nameid=viewstate["NameID"]. ToString ();

5.Cache Object
The cache object is used to save pages or data between HTTP requests. The use of this object can greatly improve the efficiency of the entire application. Often used to store a large number of frequently accessed server resources in memory, when the user makes the same request, the server does not process it again, but returns the information saved in the cache to the user, saving the server time to process the request. Its lifetime depends on the lifetime of the application. When you restart the application, an instance of its cache object is recreated. The code for saving information using the cache object is as follows.

Store information
cache["NameID"]= "0001";
Store information
Cache.Insert ("NameID", "0001", 1);
Reading information
String nameid=cache["NameID"]. ToString ();

6. hidden Fields
The hidden control is a server control of the HTML type that can be used to implement the functionality of a hidden field. In fact, the use of this control and other server controls is not very different, except that it is not displayed in the client's browser and is always hidden. But each time the page commits, this control is committed to the server side with the other server controls, so you can use the Value property on the server side to get or save some data information. The code for saving information using the hidden control is as follows.

Store information
Hidden.value= "0001";
Get information
String Nameid=hidden.value;

7. Query string
The query string is done by connecting the value to be passed behind the URL, and then using the Response.Redirect method to implement client redirection. This approach allows information to be passed between two pages. Because the length of the URL is limited, it is not possible to pass too much information, and the addition of security is not very good.
The delivery information is as follows. Question mark after format key1=value1&key2=value2

Response.Redirect ("list.aspx?nameid=0001&gradeid=002");
After executing the above statement, the code for the URL displayed in the IE Address bar follows.
http://localhost/List.aspx?nameID=0001&grade=002
When you jump to list.aspx, you can get the information you've passed through the following code.
string Nameid.gradeid;
nameid=request.params["NameID"];
gradeid=request.params["Gradeid"];

Object usages and differences (RPM) for ASP. Application,session,cookie and ViewState

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.