The System.Web.SessionState.HttpSessionState
object provides a way to persist values between HTTP requests. In the example below, a user's preference for warnings is being saved in the session. Later on, while serving another request to the user, the application can read this preference from session and hide the warnings.
public partial class Default : System.Web.UI.Page
{
public void LoadPreferences(object sender, EventArgs args)
{
// ...
// ... A DB operation that loads the user's preferences.
// ...
// Store a value with the key showWarnings
HttpContext.Current.Session["showWarnings"] = false;
}
public void button2Clicked(object sender, EventArgs args)
{
// While processing another request, access this value.
bool showWarnings = (bool)HttpContext.Current.Session["showWarnings"];
lblWarnings.Visible = false;
}
}
Note that the session variables are not common for all users (just like cookies), and they are persisted across multiple post-backs.
The session works by setting a cookie that contains an identifier for the users session. By default this identifier is stored in the web-server memory, along with the values stored against it.
Here is a screenshot of the cookie set in the user's browser to keep track of the session: