Click here to Skip to main content
Licence CPOL
First Posted 5 Oct 2004
Views 105,183
Bookmarked 39 times

Simple ASP.NET Session Management Framework

By | 5 Oct 2004 | Article
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.

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.

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.

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.

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)

About the Author

Joey Chömpff

Architect

Netherlands Netherlands

Member

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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalcreate sessionid Pinmemberpooran singh niranjan19:49 3 Jan '10  
GeneralInstead of cache can I use DB Pinmemberhi_from_rajiv22:12 25 Oct '09  
Generalvery important Pinmembereng_maioia11:33 16 Jun '09  
GeneralCreating New Session ID on clicking a URL Pinmemberjigneshkvp19:48 19 Feb '08  
GeneralProblem with generate first SessionID - SessionSystem.NullReferenceException Pinmembersentia4:16 29 Nov '06  
GeneralRe: Problem with generate first SessionID - SessionSystem.NullReferenceException PinmemberJoey Chömpff5:07 29 Nov '06  
GeneralProblem when generating GUID Pinmembereltommy0:57 13 Jan '06  
GeneralRe: Problem when generating GUID PinmemberJoey Chömpff1:11 13 Jan '06  
GeneralRe: Problem when generating GUID Pinmembereltommy1:39 13 Jan '06  
GeneralRe: Problem when generating GUID PinmemberJoey Chömpff1:59 13 Jan '06  
GeneralRe: Problem when generating GUID Pinmembereltommy2:08 13 Jan '06  
GeneralRe: Problem when generating GUID PinmemberJoey Chömpff2:21 13 Jan '06  
GeneralSession Problem PinmembervenkatesanN3:54 26 Sep '05  
Questionhow do I persist the sessionId Pinmemberkarthik00073:46 26 Apr '05  
AnswerRe: how do I persist the sessionId PinmemberJoey Chömpff3:50 26 Apr '05  
GeneralRe: how do I persist the sessionId PinsussAnonymous3:56 26 Apr '05  
GeneralRe: how do I persist the sessionId PinmemberJoey Chömpff20:49 26 Apr '05  
GeneralExample on Using this method Pinmembermisha20000:08 9 Dec '04  
GeneralRe: Example on Using this method PinmemberJoey Chömpff0:48 9 Dec '04  
QuestionCould you explain? PinmemberBill SerGio, The Infomercial King2:20 25 Nov '04  
AnswerRe: Could you explain? PinmemberJoey Chömpff2:36 25 Nov '04  
GeneralRe: Could you explain? PinmemberKakss19:42 30 Jan '06  
GeneralRe: Could you explain? PinmemberJoey Chömpff22:12 30 Jan '06  
GeneralRe: Could you explain? PinmemberKakss11:50 31 Jan '06  
GeneralRe: Could you explain? PinmemberJoey Chömpff2:44 1 Feb '06  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 5 Oct 2004
Article Copyright 2004 by Joey Chömpff
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid