We often use session objects to store user-specific information. Sometimes we get a requirement to get all the values in the Session object. For example, in Page1.aspx I am storing one value to the session and in Page2.aspx it is storing another value (a different key) in the session. In Page3.aspx I need to print all values.
Let's proceed to see how to get all the values in the session.
Page1.aspx.cs
In this page we are storing one value (Id) to the session.
Page2.aspx.cs
In this page we are storing another value (Name) to the session.
- Session["Name"] = "Manas Mohapatra";
Page3.aspx.csNow we will retrieve all session values that are stored in the preceding pages. It can be done using the following options.
Option 1In the following code we are looping over Session.Contents to get all the keys in the session. Later, using the key, we are getting the value from the session.
- protected void Page_Load(object sender, EventArgs e)
- {
- foreach(string key in Session.Contents)
- {
- string value = "Key: " + key +", Value: " + Session[key].ToString();
-
- Response.Write(value);
- }
- }
Option 2In the following code we are counting the number of keys present in the current session object. And using the session keys we are getting the values.
- protected void Page_Load(object sender, EventArgs e)
- {
- for (int i = 0; i < Session.Count; i++)
- {
- string value = "Key: " + Session.Keys[i] + ", Value: " + Session[Session.Keys[i]].ToString();
-
- Response.Write(value);
- }
- }
Option 3In the following code we are directly looping over the session that returns the key. Using that key we are getting the session values.
- protected void Page_Load(object sender, EventArgs e)
- {
- foreach (string s in Session)
- {
- string value = "Key: " + s + ", Value: " + Session[s].ToString();
-
- Response.Write(value);
- }
- }
OutputSee Figure 1 that shows the session key name and session value. We are looping over
Session.Contents that holds all session keys. And using the key we are getting the session values.
Figure 1: Debugging to get all the values in the session
I hope this helps you how to get all the values in the session.