Tuesday, September 30, 2008

Incorrectly Storing Objects In The ASP.NET Session

In an effort to keep this from happening to someone else, I figured I'd write about it today. I'm surely not the first person to ever write about this, so I'm not claiming to have found something novel. I've personally never written a web application that needed to utilize the ASP.NET Session object, but apparently other folks have not learned that.

Anyway, the following chunk of code was being used to store a reference to the "domain object" currently being viewed/edited.

namespace Your.Web
{
/// <summary>
/// Summary description for ContainerBase.
/// </summary>
public class ContainerBase : Page
{
public virtual IDomainObject DomainObject
{
get
{
if (Session["DomainObject"] != null)
{
return (IDomainObject) Session["DomainObject"];
}
else
{
return null;
}
}
set { Session["DomainObject"] = value; }
}
}
}

The result of doing this is that by opening one "domain object" (DO1) for editing in a window (W1), hitting CTRL-N to open a new window (W2) that by default will still show DO1, navigating to a new domain object (DO2) in W2, then switching back to W1 and clicking the Save button without any other operations, the edits in W1 that should be being applied to DO1 are actually being applied to DO2. Dooh!!!! That eliminates a user's ability to have two or more web browser windows open at a time. MS-DOS, here we come!

Moral of the story, don't use the Session object, unless you really truly have read everything there is about using it and are still convinced that you should still use it. And even then, you're probably still wrong!

For further reading, see the ASP.NET Session State Overview on MSDN.

No comments: