views:

231

answers:

2

Is it safe to access asp.net session variables through static properties of a static object?

Here is what I mean:

public static class SessionHelper
{
    public static int Age
    {
        get
        {
            return (int)HttpContext.Current.Session["Age"];
        }

        set
        {
            HttpContext.Current.Session["Age"] = value;
        }
    }


    public static string Name
    {
        get
        {
            return (string)HttpContext.Current.Session["Name"];
        }

        set
        {
            HttpContext.Current.Session["Name"] = value;
        }
    }
}

Is it possible that userA could access userB's session data this way?

+7  A: 

Yes, that way is fine - just make sure you don't do this:

public static class SessionHelper
{

    private static HttpSession sess = HttpContext.Current.Session;
    public static int Age
    {
        get
        {
            return (int)sess["Age"];
        }

        set
        {
            sess["Age"] = value;
        }
    }
}

As ive seen this way show one user's session data to another user. (Albeit in ASP.NET 1.1)

Jamiec
+1 That is a huge pain waiting to happen.
Greg
+4  A: 

IMHO, this is actually a good approach. It is type safe, add that level abstraction that could allow you to change things with minimal impact.

An example of something you might change, if you decided some state should move to the cache or even the database combined with caching, these would require additional thread synchronization, but could all be handled by the internals of this class. You might consider changing name of the class to something less session specific.

The one comment I would have on your particular example is that you should check that the Session variable is not null and either return an appropriate default, assert or raise an informative exception if it is. Just in case the property is read before it is being set.

Chris Taylor