0

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.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Liron Harel
  • 10,819
  • 26
  • 118
  • 217

3 Answers3

5

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.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
mcse3010
  • 174
  • 2
  • 10
1

HttpContext will be different for every request so yes.

Avi
  • 1,924
  • 3
  • 17
  • 31
1

This will give you a error(calling non-static method from static method.). Please refer this :-

calling non-static method in static method in Java

Community
  • 1
  • 1
Sahi
  • 1,454
  • 1
  • 13
  • 32