SoFunction
Updated on 2025-03-06

Detailed explanation of the usage of session in C#

Session has the following characteristics:

(1) The data in the Session is stored on the server side;

(2) Any type of data can be saved in the Session;

(2) The default life cycle of Session is 20 minutes, and it can be manually set to a longer or shorter time.

It should be noted that storing too much data in the Session variable will consume more server resources. You should be careful when using session.

Save string:

  Session["userName"] = "aaa";

This way the value:

string str = Session["userName"].ToString();

What is the number of a record:
  

 Session["id"] = 1;

This way the value:

  int id1 = Convert.ToInt32(Session["userName"]);

This is usually written when obtaining a session:string username=session[“username”], but when assigning values ​​to objects, we need to pay attention to two points

1: Determine whether it is null

2: Type conversion

Release method: Clear a Session

Session["UserName"] = null;
 ("UserName");

Clear all Sessions

();
 ();

Summarize

The above is the usage of session in C# that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time!