Tigraine

Daniel Hoelbling-Inzko talks about programming

Session handling in ASP.NET

Posted by Daniel Hölbling on July 17, 2008

Often you need to save data to a user-central location (something like a global variable per user) and you immediately think of the session as the perfect place to store that data.
So you have this just retrieved user-id and you go:

Session["userid"] = userid;

And this works perfectly fine, ASP.NET will take care of the cookie handling etc while you can conveniently read from this field from now on.
But, there is one catch (as always):

Accessing session data is a very error prone process and should never left to the business code itself. Whenever a session times out you'll get NullPointerExceptions cluttered throughout your application (because reading from Session["userid"] will quietly return null if the session isn't there or got lost).
Working directly with the session also robs you of all the type-checking goodness we are all used to from .NET, so you may get some InvalidCastExceptions while accessing your objects too.


And, whenever you call Session["useid"] you're risking spelling mistakes what would lead to completely bogus data.

So, I hope you get my point, working with the session object directly is really nothing you'd want to do over and over again (and therefore risking errors every time).
It's usually much better to centralize this in one spot and test that well.


And centralizing this can be easily done through creating a custom class for this that will not only keep the session object away from you, but also provide you type-safe access to your data.

I suggest starting off with the session data object that we will use to store our data in:

[Serializable()]
public class UserSessionData
{
    public int UserId
    { get; set; }
}

Notice that I've put the Serializable() attribute onto the class so if you want to store the session in a state server or in sql server the CLR knows how to serialize the object and store it.
The whole object is solely responsible for keeping our UserId, nothing more nothing less.

And now we need to store this object in the session, for that purpose we could just incorporate static methods into the class that would retrieve and set the object to the current session.
Because we're working with ASP.NET here we want this UserSessionData to be accessible from within our ASP.NET Webform so it's pretty cool to just subclass Web.UI.Page and use it afterwards as the base class for our Webforms:

public class SessionHandler : System.Web.UI.Page
{
    private const string SESSION_NAME = "UserSession";
    public UserSessionData SessionData
    {
        get
        {
            UserSessionData sessionData = (UserSessionData)Session[SESSION_NAME];
            if (sessionData != null)
                return sessionData;
            else
                throw new Exception("Could not retrieve session state");
        }
        set
        {
            Session[SESSION_NAME] = value;
        }
    }
}

Now we only need to open our code-behind file and change it's superclass from Page to our SessionHandler (that just wraps Page):

public partial class _Default : SessionHandler
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = this.SessionData.UserId.ToString();
    }   
}

Now whenever you need to read the UserId there is this neat property called SessionData that knows all about your user, while you don't need to do any is-null checks any more in your code, that's all handled by the SessionHandler class when accessing the session object :).

Hope this helps!

Filed under net, programmierung
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more