Thursday, October 1, 2009

How to use Session in ASP.Net

The traditional way of using Session in ASP.Net/C#/VB.Net has been to use Session["variablename"].

Disadvantages of using Session this ways is:
* You could have typo in the variable name and can get errors that takes time to figure out the reason.
* Session["x"] will return an object that you would have to convert to the type that you need
* You never know what are all the session variables used in the application and what is the size of session at any given time
* There is no intellisense to tell you if a Session variable already exists
* Different developers may use different names to store the same information in session

A better approach of using Session is to create a (semi)singleton class as following.

public class SiteSession
{
private object _lock = new object();

//do not allow creating new objects of this
private SiteSession()
{ ; }

public static SiteSession Current
{
get
{
if(HttpContext.Current.Session["SiteSession"] == null)
{
lock(_lock)
{
if(HttpContext.Current.Session["SiteSession"] == null)
HttpContext.Current.Session["SiteSession"] = new SiteSession();
}
}
return (HttpContext.Current.Session["SiteSession"] as SiteSession);
}
}

public string SessionVar1 { get; set; }
public int SessionVar2 { get; set;}
}

public class BasePage : System.UI.Web.Page
{
public SiteSession MySession { get { return SiteSession.Current; } }
}

Now, whenever you use SiteSession.Current or MySession in the pages, you will see the intellisense for your session variable. This now helps keep all session variables at one spot.
Also there is no typo any more. You don't have do the type conversion anymore.

You can also create a base-class for your user controls and add MySession property to that user control. So, you will be able to access the session variables easily from your user control as well.

In your static/page methods/web methods, you can use SiteSession.Current to access the session variables.

No comments:

Post a Comment