Click here to Skip to main content
14,737,146 members
Articles » Web Development » Session State » Sessions and Session State
Article
Posted 5 Oct 2004

Stats

143.6K views
1.2K downloads
42 bookmarked

Simple ASP.NET Session Management Framework

Rate me:
Please Sign up or sign in to vote.
2.64/5 (10 votes)
5 Oct 2004CPOL
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)

Share

About the Author

Joey Chömpff
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 20:49
Memberpooran singh niranjan3-Jan-10 20:49 
GeneralInstead of cache can I use DB Pin
hi_from_rajiv25-Oct-09 23:12
Memberhi_from_rajiv25-Oct-09 23:12 
Generalvery important Pin
eng_maioia16-Jun-09 12:33
Membereng_maioia16-Jun-09 12:33 
GeneralCreating New Session ID on clicking a URL Pin
jigneshkvp19-Feb-08 20:48
Memberjigneshkvp19-Feb-08 20:48 
GeneralProblem with generate first SessionID - SessionSystem.NullReferenceException Pin
sentia29-Nov-06 5:16
Membersentia29-Nov-06 5:16 
GeneralRe: Problem with generate first SessionID - SessionSystem.NullReferenceException Pin
Joey Chömpff29-Nov-06 6:07
MemberJoey Chömpff29-Nov-06 6:07 
GeneralProblem when generating GUID Pin
eltommy13-Jan-06 1:57
Membereltommy13-Jan-06 1:57 
GeneralRe: Problem when generating GUID Pin
Joey Chömpff13-Jan-06 2:11
MemberJoey Chömpff13-Jan-06 2:11 
GeneralRe: Problem when generating GUID Pin
eltommy13-Jan-06 2:39
Membereltommy13-Jan-06 2:39 
GeneralRe: Problem when generating GUID Pin
Joey Chömpff13-Jan-06 2:59
MemberJoey Chömpff13-Jan-06 2:59 
GeneralRe: Problem when generating GUID Pin
eltommy13-Jan-06 3:08
Membereltommy13-Jan-06 3:08 
GeneralRe: Problem when generating GUID Pin
Joey Chömpff13-Jan-06 3:21
MemberJoey Chömpff13-Jan-06 3:21 
GeneralSession Problem Pin
Member 196637026-Sep-05 4:54
MemberMember 196637026-Sep-05 4:54 
Questionhow do I persist the sessionId Pin
karthik000726-Apr-05 4:46
Memberkarthik000726-Apr-05 4:46 
AnswerRe: how do I persist the sessionId Pin
Joey Chömpff26-Apr-05 4:50
MemberJoey Chömpff26-Apr-05 4:50 
GeneralRe: how do I persist the sessionId Pin
Anonymous26-Apr-05 4:56
MemberAnonymous26-Apr-05 4:56 
GeneralRe: how do I persist the sessionId Pin
Joey Chömpff26-Apr-05 21:49
MemberJoey Chömpff26-Apr-05 21:49 
GeneralExample on Using this method Pin
misha20009-Dec-04 1:08
Membermisha20009-Dec-04 1:08 
GeneralRe: Example on Using this method Pin
Joey Chömpff9-Dec-04 1:48
MemberJoey Chömpff9-Dec-04 1:48 
QuestionCould you explain? Pin
William SerGio25-Nov-04 3:20
professionalWilliam SerGio25-Nov-04 3:20 
AnswerRe: Could you explain? Pin
Joey Chömpff25-Nov-04 3:36
MemberJoey Chömpff25-Nov-04 3:36 
GeneralRe: Could you explain? Pin
Kakss30-Jan-06 20:42
professionalKakss30-Jan-06 20:42 
GeneralRe: Could you explain? Pin
Joey Chömpff30-Jan-06 23:12
MemberJoey Chömpff30-Jan-06 23:12 
GeneralRe: Could you explain? Pin
Kakss31-Jan-06 12:50
professionalKakss31-Jan-06 12:50 
GeneralRe: Could you explain? Pin
Joey Chömpff1-Feb-06 3:44
MemberJoey Chömpff1-Feb-06 3: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.