Does static reference to HttpContext.Current.Session return same session for all users?

我与影子孤独终老i 提交于 2020-01-11 03:10:07

问题


Is there room for issue in the following code in terms of multiple users of the same web application? I mean, I know that a purely static string will be shared across all sessions for a single ASP.NET application, but given that this explicitly refers to the Current.Session, even though it is static it seems like it would always refer to the session instance of the "current user."

But an error is happening that could be explained by everyone sharing the current value of Mode and thus the most recent change overwriting everyone else's mode value.

(As a background: This string is in a Helpers class that is used throughout the application. I do not want to make hard-coded references to Session["Mode"] throughout the application and do not want to have to pass Session["Mode"] in every method call from an aspx.cs page.)

public static string Mode
{
    get
    {
        var value = HttpContext.Current.Session["Mode"];
        return (value ?? string.Empty).ToString();
    }
    set
    {
        HttpContext.Current.Session["Mode"] = value;
    }
}

回答1:


HttpContext.Current always returns the context of the current request (if there is a current request).

Since each user will be executing a different request, each context will be different.




回答2:


Your property is static. This is actually the cause of sharing the property between users.

See Scope of static Variable in multi-user ASP.NET web application for more details.



来源:https://stackoverflow.com/questions/4899432/does-static-reference-to-httpcontext-current-session-return-same-session-for-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!