Click here to Skip to main content
15,867,834 members
Articles / Web Development / HTML
Article

Simple ASP.NET Session Management Framework

Rate me:
Please Sign up or sign in to vote.
2.64/5 (10 votes)
5 Oct 2004CPOL2 min read 150.6K   1.2K   42   30
An article on managing Session information.

Introduction

For a project of my former employer, I’ve run into a problem of losing Session information after communication with other applications on different domains. My ASP.NET application was communicating via hidden-fields through a POST on a Java-Servlet and PHP pages. These pages get my postback-aspx-URL but after the postback, I lose the Session information because these applications where running on a different domain.

That's why I've looked for the possibilities in ASP.NET for storing Session information, without using difficult State-Management-servers or databases.

Creating the framework

ASP.NET developers are familiar with the objects Session and Cache, these objects are central in my framework for managing Session information.

I’ve started creating an object for storing Session information, named SessionObject. See listing 1. In this object, you can place your variables needed for your sessions.

C#
public class SessionObject
{
  private string _userName = string.Empty;

  public string UserName
  {
    get { return _userName; }
    set { _userName = value; }
  }
}

Listing 1. SessionObject.cs

Thereafter, I’ve been thinking how I can get SessionObject back. In ASP.NET there is an object called Cache. This object is created on each Application-Domain and is type-safe on multi-threaded applications. Don’t forget that when your ASP.NET application is unloaded by the WebServer, your Cache object is also flushed. See listing 2.

C#
public class SessionManager
{
  private const string SESSION_MANAGER = "SessionManager";
  private HttpContext _context;
  private Guid _sessionID;
  private SessionObject _sessionObject;

  public SessionManager (HttpContext httpContext)
  {
    _context = httpContext;
  }
  public static void Initialize(HttpContext httpContext)
  {
    httpContext.Items.Add(SESSION_MANAGER, new SessionManager (httpContext));
  }
  public static SessionManager Current
  {
    get { return (SessionManager) HttpContext.Current.Items[SESSION_MANAGER]; }
  }

  public Guid SessionID
  {
    get { return _sessionID; }
    set
    { 
      if (!_sessionID.Equals(value))
      {
        _sessionID = value;
        GetSessionObject(value);
       }
    }
  }
  private void GetSessionObject(Guid sessionID)
  {
    _sessionObject = _context.Cache[sessionID.ToString()] as SessionObject;
    if (_sessionObject == null)
      SetSessionObject(sessionID, new SessionObject());
  }

  private void SetSessionObject(Guid sessionID, SessionObject sessionObject)
  {
    _context.Cache.Add(sessionID.ToString(), 
      sessionObject,
      null,
      DateTime.MaxValue,
      TimeSpan.FromHours(2),
      System.Web.Caching.CacheItemPriority.High,
      null);
    _sessionObject = sessionObject;
  }

  public SessionObject SessionObject
  {
    get { return _sessionObject; }
  }
}

Listing 2. SessionManager.cs

The SessionManager uses a SessionID, this is stored in the Session object (not our SessionObject) or it will be returned by a QueryString variable of ASPX-page. On every request on the ASP.NET application, the SessionManager is initialized and added on the HttpContext.Items.

C#
protected void Application_BeginRequest(Object sender, EventArgs e)
{
  Chompff.SessionManager.Web.SessionManager.Initialize(Context);
}

Listing 3. Global.asax.cs

By creating a base ASPX-page where all other ASPX-pages derive from, with a property SessionManager, you have access to the SessionManager on all other ASPX-pages. But it’s possible that the SessionManager doesn’t have a SessionObject initialized. Therefore, we create a property SessionID, and by setting the SessionID of the base ASPX-page, the SessionManager gets the SessionObject from the Cache, or when it doesn’t exist, it creates one and places it in the Cache. See listing 4.

C#
public class BaseWebForm : System.Web.UI.Page
{
  private void Page_Load(object sender, System.EventArgs e)
  {
    // Put user code to initialize the page here
  }
  public SessionManager SessionManager
  {
    get { return SessionManager.Current; }
  }

  public Guid SessionID
  {
    get { return (Guid) Session["SessionID"]; }
    set
    {
      Session["SessionID"] = value;
      SessionManager.SessionID = value;
    }
  }
  override protected void OnInit(EventArgs e)
  {
    InitializeComponent();
    base.OnInit(e);
  }
  private void InitializeComponent()
  {
    this.Load += new System.EventHandler(this.Page_Load);
  }
}

Listing 4. BaseWebForm.cs

In every ASP.NET application, there is a start page. This page has to create a new SessionID by executing in the Page_Load: this.SessionID = Guid.NewGuid;. Now, there is a SessionObject created in the Cache, and you can get the Session information on every other ASPX-page by setting SessionID on that page.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Netherlands Netherlands
Joey Chömpff is an allround developer, who started with Pascal and worked his way up with Delphi. Since 2003 he is working with the Microsoft.NET framework, he is specialized in C# and has worked with several Microsoft products.

Comments and Discussions

 
Generalcreate sessionid Pin
pooran singh niranjan3-Jan-10 19:49
pooran singh niranjan3-Jan-10 19:49 
GeneralInstead of cache can I use DB Pin
hi_from_rajiv25-Oct-09 22:12
hi_from_rajiv25-Oct-09 22:12 
Generalvery important Pin
eng_maioia16-Jun-09 11:33
eng_maioia16-Jun-09 11:33 
GeneralCreating New Session ID on clicking a URL Pin
jigneshkvp19-Feb-08 19:48
jigneshkvp19-Feb-08 19:48 
GeneralProblem with generate first SessionID - SessionSystem.NullReferenceException Pin
sentia29-Nov-06 4:16
sentia29-Nov-06 4:16 
GeneralRe: Problem with generate first SessionID - SessionSystem.NullReferenceException Pin
Joey Chömpff29-Nov-06 5:07
Joey Chömpff29-Nov-06 5:07 
GeneralProblem when generating GUID Pin
eltommy13-Jan-06 0:57
eltommy13-Jan-06 0:57 
GeneralRe: Problem when generating GUID Pin
Joey Chömpff13-Jan-06 1:11
Joey Chömpff13-Jan-06 1:11 
GeneralRe: Problem when generating GUID Pin
eltommy13-Jan-06 1:39
eltommy13-Jan-06 1:39 
GeneralRe: Problem when generating GUID Pin
Joey Chömpff13-Jan-06 1:59
Joey Chömpff13-Jan-06 1:59 
GeneralRe: Problem when generating GUID Pin
eltommy13-Jan-06 2:08
eltommy13-Jan-06 2:08 
GeneralRe: Problem when generating GUID Pin
Joey Chömpff13-Jan-06 2:21
Joey Chömpff13-Jan-06 2:21 
GeneralSession Problem Pin
Member 196637026-Sep-05 3:54
Member 196637026-Sep-05 3:54 
Questionhow do I persist the sessionId Pin
karthik000726-Apr-05 3:46
karthik000726-Apr-05 3:46 
AnswerRe: how do I persist the sessionId Pin
Joey Chömpff26-Apr-05 3:50
Joey Chömpff26-Apr-05 3:50 
GeneralRe: how do I persist the sessionId Pin
Anonymous26-Apr-05 3:56
Anonymous26-Apr-05 3:56 
GeneralRe: how do I persist the sessionId Pin
Joey Chömpff26-Apr-05 20:49
Joey Chömpff26-Apr-05 20:49 
GeneralExample on Using this method Pin
misha20009-Dec-04 0:08
misha20009-Dec-04 0:08 
GeneralRe: Example on Using this method Pin
Joey Chömpff9-Dec-04 0:48
Joey Chömpff9-Dec-04 0:48 
QuestionCould you explain? Pin
Bill SerGio, The Infomercial King25-Nov-04 2:20
Bill SerGio, The Infomercial King25-Nov-04 2:20 
AnswerRe: Could you explain? Pin
Joey Chömpff25-Nov-04 2:36
Joey Chömpff25-Nov-04 2:36 
GeneralRe: Could you explain? Pin
Kakss30-Jan-06 19:42
professionalKakss30-Jan-06 19:42 
GeneralRe: Could you explain? Pin
Joey Chömpff30-Jan-06 22:12
Joey Chömpff30-Jan-06 22:12 
GeneralRe: Could you explain? Pin
Kakss31-Jan-06 11:50
professionalKakss31-Jan-06 11:50 
GeneralRe: Could you explain? Pin
Joey Chömpff1-Feb-06 2:44
Joey Chömpff1-Feb-06 2:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.