Search code examples
c#asp.netsession-variablesstatic-classes

Static class and Session variables


I have defined a static class. In that static class I have the following method.

public static int GetUserId()
{
    if(IsUserLoggedIn())
    {
        return Convert.ToInt16(HttpContext.Current.Session["user"]);
    }
    return 0;
}

My question is this: When that function run for each user, will each user get a different value? (considering each user session gets different userId for the Session["user"].

I don't know if a static class is useful for this or can cause conflict issues. I am developing in C#/ASP.NET.


Solution

  • In short, I believe the answer is yes, however you should avoid having hard-coded dependencies in non-factory methods... Consider accepting a HttpSessionState or at the very least a HttpContext object to act on, like so:

    public static int GetUserId(HttpContext context)
    {
        if(IsUserLoggedIn())
        {
            return Convert.ToInt16(context.Session["user"]);
        }
        return 0;
    }
    

    You should, however, likely be using the built in IPrincipal (User) property on the HttpContext, IMHO.