简体   繁体   中英

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.

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.

HttpContext对于每个请求都会有所不同,所以可以。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM