5

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;
    }
}
Devin Burke
  • 13,642
  • 12
  • 55
  • 82
  • "Gets or sets the HttpContext object for the current HTTP request." http://msdn.microsoft.com/en-us/library/system.web.httpcontext.current.aspx – Kris Ivanov Feb 04 '11 at 15:03

2 Answers2

8

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
0

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.

Community
  • 1
  • 1
toddmo
  • 20,682
  • 14
  • 97
  • 107
  • The property is a facade over a `get` and `set` method in this case. So the fact that the data being fetched is from the local session makes references to this property session-dependent and therefore not shared between users. – Devin Burke Nov 01 '16 at 21:57
  • Since you can't call instance members from within a static member, I would review the `HttpContext.Current.Session` to see how exactly they get around this and make it user specific. If I have time I'll look it up, but the answer will be interesting. – toddmo Nov 01 '16 at 22:35