ASP.NET: Cache or Session

What the difference between Cache and Session variables. Cache variables are available at the application level which means that another web user can access the same cache. Session variables are available at the client level which only the client can read or write to the Session variable.

When developing a web application in ASP.NET it’s good practice to use Cache to store data that will be shared across the application. For example if you need to read from cache a list of colour names from a table from a database, you can reuse this cache when ever your page loads. This way it prevents repetitive reads from the table which can reduce web application performance.

List<string> colourList = new List<string>();

Cache["ColourList"] = colourList;

colourList = Cache["ColourList"] as List<string>;

Session variables are used for storing user specific data such as user’s details, below is an example of how it’s used.

Session["Username"] = "joe.bloggs";

string username = Session["Username"].ToString();

Make sure you understand the difference between them two and which one to use for your purpose, never store user’s details in a Cache variable because another web user can access them but then this means that the web was poorly designed.

For further reading on Cache and Session variables I came across some web sites that may be resourceful:

ASP.NET Session State Overview

ASP.NET Caching

Shares