Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

How To Write, Read and Delete Session State Variables

HTTP is stateless protocol which doesn't provide information if two requests come from the same visitor or from two different visitors. Data like IP address, browser type, operating system etc., are not reliable for visitor identification.

 

ASP.NET session state is one method to solve this problem. Session state can be used to identify same visitor between requests. Session variables act as global variables, visible from all .aspx pages on website. Each visitor has its own session collection which is created on first request and destroyed when session expires. By default, session expires after 20 minutes of inactivity.

How to write and read session state variables

To create, read or delete session state variables, we'll use Session property (full path is System.Web.HttpContext.Session). Session property is type of System.Web.SessionState.HttpSessionState. Writing and reading of variables is simple. An example could look like this:

[ C# ]

// Create new session variable named "MySession" and add some data
Session["MySession"] = "This is my session value";

// Second option, using Add method to specify session key as string and value as object
Session.Add("MySession", "Some value");

// Session data will persists across pages during the visit, then
// when needed, on some other page you can read variable's value
string mySession = (string)Session["MySession"];

[ VB.NET ]

' Create new session variable named "MySession" and add some data
Session("MySession") = "This is my session value"

 ' Second option, specifies session key as string and value as object
Session.Add("MySession", "Some value")

 ' Session data will persists across pages, then
 ' when needed, you can read its value
 Dim mySession As String = Session("MySession")

How to avoid possible errors when reading session

Type of all session values is System.Object, so you can store any .Net type in session state. But, when read value, you need to convert it back from Object to original type. This could lead to error if session is expired. When session is expired, variable is deleted and session object will return null value. Attempt to convert null to original type could cause a null reference error, cast error, lead to unexpected behavior in web application etc.

To avoid this, it is better to check first is session variable equal to null, and if it is null, use some default value. So, more robust code for reading session variable could look like this:

[ C# ]

// Default value, used if session is null
string DefaultTheme = "default";

string SelectedTheme = "";

 // Check if session is null
 if (Session["UserTheme"] == null)
 {
    // Value is null, so use default value
    SelectedTheme = DefaultTheme;
}
 else
 {
    // Value is not null, read actual value from session
    SelectedTheme = (string)Session["UserTheme"];
}

[ VB.NET ]

' Default value, used if session is null
Dim DefaultTheme As String = "default"

Dim SelectedTheme As String = ""

' Check if session is null
If Not (Session("UserTheme") Is Nothing) Then
  ' Value is null, so use default value
  SelectedTheme = DefaultTheme
Else
  ' Value is not null, read actual value from session
  SelectedTheme = Session("UserTheme").ToString()
End If

Session state variables act as global variables for individual visitor. They are visible from all .aspx pages. But, they are not visible for other server side technologies, like classic ASP, PHP, JSP etc. Each visitor has unique string named Session id which is used for identification, and its own session variables in form of collection of key-value pairs.

Except null value issue, one more problem when working with ASP.NET sessions could be hard coding of session variables names. Variables are hard coded in example above where name of variable "UserTheme" is written two times as plain string. Problem is even bigger if you use some variable on many pages and on every place write literals. If we want to change that variable name, from "UserTheme" to something different, it will require change in all places where this variable occurs.

Also, while coding, there is always a possibility to misspell variable name. In that case ASP.NET will not return an error or warning. It will simply assume that this is a second variable with slightly different name. So, for names of session variables, better avoid hard coded strings. You can store names in some public class but that solves only part of the maintenance problems.

Manipulate session by using wrapper class

As better solution that solves all these problems, you can create a wrapper class. Wrapper class will have static properties which will represent session variables. On this way, complete session code is on single place which is easy to maintain. On pages, use wrapper class property to read or write session variable:

A SessionWrapper class, with one example property that represents session variable "UserTheme", could look like this:

[ C# ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class SessionWrapper
{

  public SessionWrapper()
  {

  }

  public static string UserTheme
  {
    get
    {
    // Gets object from session
    Object objUserTheme = HttpContext.Current.Session["UserTheme"];
    // Check if value is null
    if (objUserTheme == null)
    {
    // If value is null, return default value
    return "DefaultTheme";
}
    else
    {
    // If value is not null, return it
    return (string)objUserTheme;
}
}
    set
    {
    // Adds value to session variable
    HttpContext.Current.Session["UserTheme"] = value;
}

}
}

[ VB.NET ]

Public Class SessionWrapper
  Public Shared Property UserTheme() As String
    Get

    ' Gets object from session
    Dim objUserTheme As Object = HttpContext.Current.Session("UserTheme")
    ' Check if value is null
    If objUserTheme Is Nothing Then
    ' If value is null, return default value
    Return "DefaultTheme"
    Else
    ' If value is not null, return it
    Return objUserTheme.ToString()
    End If
  End Get
  Set(ByVal value As String)
    ' Adds value to session variable
    HttpContext.Current.Session("UserTheme") = value
  End Set

 End Property
End Class

You can add as many properties as you have session variables, and add new item when needed. Save this class to website's App_Code folder. To call example session variable "UserTheme" on any .aspx page, simply use SessioinWrapper.UserTheme, like bolded part in next example:

[ C# ]

protected void Page_Load(object sender, EventArgs e)
{  
    Response.Write(SessionWrapper.UserTheme);  
}

[ VB.NET ]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Response.Write(SessionWrapper.UserTheme)
End Sub

SessionWrapper class logic is very simple, but powerful. It solves all common problems when coding sessions:
 
- Static property could return an object of appropriate type, without need to convert it on every page and repeat same code,
- Default value is returned if current value is null, so you'll not get an exception message,
- Since you call a property, you can't misspell session variable name on some page (this type of error could be hard to discover),
- You don't repeat same code over multiple pages which is good for maintenance. Every issue, like type conversion, default value, variable names etc., is handled on single place and easily changed.

How to delete session variables or complete session

If visitor is not made any request in time interval longer than specified with sessionTimeout parameter (20 minutes by default), that session will be deleted. This is automatic process used by ASP.NET  to save server resources.

You can also delete complete session or just some variables using ASP.NET server side code. To delete all session data, including session itself, use:

Session.Abandon()

Calling of Session.Abandon will destroy current session and invoke Session_End event. Notice that session id will still exist after Session.Abandon is called. In case that visitor proceed on some other page, new session will be created with same session id. Session id is deleted when sessoin expires on timeout.

To delete only one session variable, use Session.Remove method. For example, to delete variable named "UserTheme", use:

Session.Remove("UserTheme");

To remove all keys and values, but keep session active, use:

Session.RemoveAll();

As you see, Session.Abandon and Session.RemoveAll are very similar. They both delete all session variables. Difference is that Session.Abandon also destroyes a session, while Session.RemoveAll just clears collection. If InProc mode is used, Session.Abandon will invoke Session_End event.

Conclusion

As you see, working with ASP.NET sessions is simple. But, you should take care of few simple tips to avoid possible bugs or maintenance problems in the future. Using of wrapper class can simplify working with sessions, especially if you have large project.

If session expires, all its variables are deleted. This could be a problem in some scenarios. If you need to keep your sessions alive while visitor is working on some long task, like filling of long order form or reading a license agreement, see How To Keep ASP.NET Session Alive tutorial.

Happy Coding!


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   


comments powered by Disqus