asp.net page state management cookie and server state management Session

  • 2020-05-10 18:01:20
  • OfStack

Cookie: a small amount of data stored in memory in a text file on the client file system or in a client browser conversation on the client browser. When we visit a web page, when the user requests the web page, the application will first check whether the user has already logged in before, and we can read Cookie to get the user information to determine whether to let it continue to visit


Record Cookie information
Create an Cookie object with the name user: HttpCookie cookie=new HttpCookie("user");
To assign a value to Cookie, use only strings: cookie. Value="chenxiaomei";
If you have multiple strings to save, you can do this by:
cookie [" sex "] = "female";
cookie.Values.Add("age","18");


Read Cookie information
 
HttpCookie cookie = Request.Cookies["user"]; 
if (null==cookie) 
{ 
Response.Write(" Not found formulated cookie"); 
} 
else 
{ 
Response.Write("cookie All values of: " + cookie.Value + "<br/>"); 
Response.Write("sex A value of :" + cookie["sex"] + "<br/>"); 
Response.Write("age Value is: " + cookie["age"] + "<br/>"); 
} 

Delete Cookie
Since Cookie is saved on the client side, you can ask the browser to delete Cookie for you. Set the value of Cookie to the past
Some date.
cookie.Expires = DateTime.Now.AddHours(-1);

Session object
When the user establishes a connection with the server for the first time, he establishes an Session with the server and the server will

An SessionID is automatically assigned to identify this user as a one-only identity.
Specific operation of Session:
 
// Store information  
Session["myname"] = "chenxiaomei"; 
// Access to information  
string myname = Session["myname"]; 
// remove session 
Session.Clear();// from Session Remove all keys and values from the state set  
Session.Abandon();// Cancel the current Session The session  



Differences between Session and Cookie:
Information is stored in different places and for different periods of time
Cookie is a text file that the web server stores on the web client's hard drive. The web server requests the web client to store 1 piece of information, which can be saved in Cookie. After that, every time the client requests a page from the server, it will send the information back to the server.
The Session variable will create one dictionary object for each connection on the server, saved using the server side. While Cookie may have an invalidated date by year, month, and day, an Session level variable becomes invalidated when the connection times out

Related articles: