Click here to Skip to main content
Click here to Skip to main content

Control what developers store in ASP.NET Session

, 18 Mar 2007
Rate this:
Please Sign up or sign in to vote.
This article suggests a way to encapsulate what is stored in ASP.NET session and provides a typesafe way to store objects in session.

Introduction

This article suggests a way to encapsulate what is stored in ASP.NET session and provides a typesafe way to store objects in session.

Background

ASP.NET provides Session object to save information across http requests. But I have seen developers using Session object indiscriminately. At times, we even store those objects in session which could be stored in context i.e just to pass information
from one aspx page to another (in case of Server.Transfer() and Server.Execute())

This article suggests a way which allows you to store data in session through a single object of SessionData class. To store any object in session, developers do not store it directly in session. Instead, a property for the object to be stored is added to the SessionData class. As a result, the SessionData class has all the objects stored in session exposed as property. The advantages are:

1. It provides a centralised location for storing session data. To store any object in session, developers have to add a property to the class. So you have control over what is stored in session. Developers would be discouraged to store whatever in session.

2. Provides a type safe interface to storing objects in session.

Using the code

Add the SessionData class to your ASP.NET project. In ASP.NET 2.0, this gets added to App_Code folder.

using System;
using System.Web.SessionState;
/// <span class="code-SummaryComment"><summary>
</span>
/// This class encapsulates all data stored in session for a user
/// <span class="code-SummaryComment"></summary>
</span>
public class <code> SessionData 
{
    #region private members
    
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Session for the user
    /// <span class="code-SummaryComment"></summary>
</span>
    private HttpSessionState session = null;
 
    #endregion

    #region Constructors
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Constructor
    /// <span class="code-SummaryComment"><param name="session">User Session</param>
</span>
    /// <span class="code-SummaryComment"></summary>
</span>
    public SessionData(HttpSessionState session)
    {
      this.session = session;        
    }
    #endregion

    #region Public Properties
 
    /// <span class="code-SummaryComment"><summary>
</span>
    /// User. This is an example of property added to SessionData class
    /// <span class="code-SummaryComment"></summary>
</span>
    public string User
    {
        get
        {
            return (string)this.session["User"];
        }
        set
        {
            this.session["User"] = value;
        }
        
    }
    #endregion
}

In the Session_Start event, add the code to create an object of SessionData object and store it in session

    void Session_Start(object sender, EventArgs e) 
    {
        // Create an object of SessionData
        SessionData sessionData = new SessionData(Session);
      // Store sessionData in session
        Session["SessionData"] = sessionData;
        sessionData.User = "Sachin";
    }
    

Add an object of SessionData as a member of all the pages. Alternatively, you can create a base page with common functionality and inherit page from the base page

public partial class _Default : System.Web.UI.Page 
{
    SessionData sessionData = null;
 .
 .
}

In the Page_Load event handler retrieve object of SessionData and store in member variable to access through out page. SessionData can also be initialized in constructor of the page. I think constructor is a better place than Page_Load event handler.

this.sessionData = (SessionData)Session["SessionData"]; 

In the Page_Load event handler retrieve object of SessionData and store in member variable to access through out page. SessionData can also be initialized in constructor of the page. I think constructor is a better place than Page_Load event handler.

 this.sessionData.User = "sachin

Points of Interest

1. Was interesting to know that Session object can'be accessed to initialize member variables.

public partial class _Default : System.Web.UI.Page </code>
{

SessionData sessionData = Session["SessionData"]; // Cannot access Session object

.
.
}

History

Keep a running update of any changes or improvements you've made here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

sachinsurana

Australia Australia
No Biography provided

Comments and Discussions

 
GeneralUnable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if simila Pinmemberatultrip30-Oct-07 4:14 
GeneralBad idea Pinmemberdanidanidani18-Mar-07 14:03 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150129.1 | Last Updated 18 Mar 2007
Article Copyright 2007 by sachinsurana
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid