Common ASP. NET objects: Cookie, Session, and Application

Source: Internet
Author: User

Common ASP. NET objects: Cookie, Session, and Application

In the previous blog, we studied Response and Request. After solving the basic value transfer problem, we will find some problems, such as passing values between two pages, when logging on, I need to maintain the session Status, count the number of online users of a website in real time, and solve the response and request, which is not convenient, and some cannot even be solved. Therefore, we have introduced cookies, sessions, and applications.

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.

1. The purpose of the Application Object in actual network development is to record the information of the entire network, such as the number of online users, online lists, opinion surveys, and online elections. Information is shared among multiple users in a given application and stored permanently during server running. In addition, the Application object also provides methods to control access to Application layer data and events that can be used to trigger the process when the Application starts or stops.
(1). Use the Application object to save information
Application ("key name") = value or Application ("key name", value)
(2). Get Application Object Information
Variable name = Application ("key name") or: variable name = Application. Item ("key name") or: variable name = Application. Get ("key name ")
(3). Update the value of the Application Object
Application. Set ("key name", value)
(4). delete a key
Application. Remove ("key name", value)
(5). Delete all keys
Application. RemoveAll () or Application. Clear ()
2. Multiple users may access the same Application object at the same time. In this way, multiple users may modify the name object of the same Application, resulting in data inconsistency.
The HttpApplicationState class provides two methods: Lock and Unlock to solve the problem of access synchronization to the Application object. Only one thread is allowed to access the Application state variable at a time.
About locking and unlocking
Lock: Application. Lock ()
Access: Application ("key name") = Value
Unlock: Application. Unlock ()
Note: the Lock and UnLock methods should be used in pairs. Used by devices such as website visitors and chat rooms
3. Use Application events
In ASP. NET Applications can contain a special optional file-Global. asax file, also known as ASP.. NET application file, which contains the file used to respond to ASP. code of application-level events caused by the NET or HTTP module.
The Global. asax file provides seven events, five of which are applied to Application objects.

Ii. 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 Session object is the number that the server sends to the client. When a WEB server is running, several users may browse the website on this server. When a user establishes a connection with the WWW server for the first time, the user establishes a Session with the server, and the server automatically assigns a SessionID to the user to identify the unique identity. It is particularly noted that the Session object variables are only valid for one user, and the Session information of different users is stored using the variables of different Session objects. In the network environment, the variables of the Session object have a life cycle. If the variables of the Session object are not refreshed at the specified time, the system terminates these variables.

Session refers to a user's access to a website within a period of time.
The Session Object corresponds to the HttpSessionState class in. NET, which indicates the "Session state" and can save information related to the current user Session.
The Session object is used to store the information required by a user to access a specific aspx page from the moment the user leaves. When you switch the page of an application, the variables of the Session object are not cleared.
For a Web Application, the content of the Application object accessed by all users is identical, while the content of the Session object accessed by different users is different.

The Session can save the variable, which can only be used by one user. That is to say, each browser has its own Session object variable, that is, the Session object is unique.
(1) Add new items to the session Status
Session (key name) = value or Session. Add (key name, value)
(2) obtain the value in the session status by name
Variable = Session (key name) or variable = Session. Item (key name)
(3) deleting items in the session Status set
Session. Remove (key name)
(4) Clear all values in the session Status
Session. RemoveAll () or Session. Clear ()
(5) cancel the current session
Session. Abandon ()
(6) set the timeout period of the session Status, in minutes.
Session. TimeOut = Value
The Global. asax file has two events applied to the Session object.
Session_Start is triggered when the session is started.
Session_End is triggered at the end of the session

Example of combining application object with session object:

 

using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security;using System.Web.SessionState;using System.Data.SqlClient;namespace applicationExample{    public class Global : System.Web.HttpApplication    {        protected void Application_Start(object sender, EventArgs e)        {            SqlConnection con = new SqlConnection(server=.;database=countPeople;uid=sa;pwd=123456;);            con.Open();            SqlCommand cmd =new SqlCommand(select * from countPeople,con);            intcount = Convert.ToInt32(cmd.ExecuteScalar());            con.Close();            Application[total]= count;            Application[online] = 0;        }        protected void Session_Start(object sender, EventArgs e)        {           Session.Timeout = 1;           Application.Lock();           Application[total] = (int)Application[total] +1;           Application[online] = (int)Application[online] +1;           Application.UnLock();        }        protected void Application_BeginRequest(object sender, EventArgs e)        {        }        protected void Application_AuthenticateRequest(object sender, EventArgs e)        {        }        protected void Application_Error(object sender, EventArgs e)        {         }        protected void Session_End(object sender, EventArgs e)        {           Application.Lock();           Application[online] = (int)Application[online]-1;           Application.UnLock();        }        protected void Application_End(object sender, EventArgs e)        {           SqlConnection con = newSqlConnection(server=.;database=countPeople;uid=sa;pwd=123456;);           con.Open();           SqlCommand cmd = new SqlCommand(update countPeople setnum=+Application[total].ToString(), con);           cmd.ExecuteNonQuery();           con.Close();        }    }}
Through the above, we can find that the application global variable, session is the session variable, for example:

 

(1) session: declares a session variable. When a website is opened, the session will exist. If the page is changed, the session will always exist. When the website is closed, the session will end. This is called the session variable.

(2) application: declare an application variable. It doesn't matter how many customers on the front-end open pages of the website, and how many customers close the pages of the website, as long as the server does not

Close the website and the application always exists.

3. Cookie object

A Cookie is a piece of text that the Web server saves on the user's hard disk. Cookie allows a Web site to save information on a user's computer and then retrieve it. Information fragments are stored as 'key/value' pairs.

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 4096. Therefore, do not store 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.
There are two types of cookies: Session Cookie and persistent Cookie. The former is temporary. Once the session state ends, it will no longer exist. The latter has a fixed expiration date, and the Cookie will be stored on the user's computer as a text file before it expires.
You can use the Response object to create a Cookie on the server and output it to the client.
The Response object supports a set named Cookies. You can add Cookie objects to the set to output Cookies to the client. Access the Cookie through the Cookie set of the Request object.

Put js in cookie:

 

 setCookie('College',strCollege); setCookie('CourseId',strCourseId);

 

Class to obtain the cookie:

HttpCookiecookieCollege =System.Web.HttpContext.Current.Request.Cookies.Get(College);stringstrCollege =Server.UrlDecode(cookieCollege.Value);        HttpCookie cookieCourseId =System.Web.HttpContext.Current.Request.Cookies.Get(CourseId);stringstrCourseId = cookieCourseId.Value;

Summary:

Method

Information size

Save time

Application Scope

Save location

Application

Any size

Entire application life cycle

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

 

You may still use global variables before, but it is not the best solution. Using cookies, sessions, or applications can help us solve the problem better.

 

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.