Retrieve Session Values in ASP.NET

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.

  1. Session["Id"] = "1";  
Page2.aspx.cs

In this page we are storing another value (Name) to the session.
  1. Session["Name"] = "Manas Mohapatra";  
Page3.aspx.cs

Now we will retrieve all session values that are stored in the preceding pages. It can be done using the following options.

Option 1

In 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.
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     foreach(string key in Session.Contents)     
  4.     {    
  5.         string value = "Key: " + key +", Value: " + Session[key].ToString();    
  6.     
  7.         Response.Write(value);    
  8.     }    
  9. }   
Option 2

In 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.
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     for (int i = 0; i < Session.Count; i++)    
  4.     {    
  5.         string value = "Key: " + Session.Keys[i] + ", Value: " + Session[Session.Keys[i]].ToString();    
  6.     
  7.         Response.Write(value);    
  8.     }    
  9. }   
Option 3

In the following code we are directly looping over the session that returns the key. Using that key we are getting the session values.
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     foreach (string s in Session)    
  4.     {    
  5.         string value = "Key: " + s + ", Value: " + Session[s].ToString();    
  6.     
  7.         Response.Write(value);    
  8.     }    
  9. }  
Output

See 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.

Debugging to get all values in Session
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.


Similar Articles