Search code examples
c#asp.nethttpcontext

HTTP Context in static class


As I know the static method of the static class is shared to all the user in a web application.
How does HttpContext.Current.Session["Key"] work in a static classes.
Since the session is created for every user.
An example below return the user name in the session

 using System.Web;

 namespace WebApplication1 
 {
    public static class UserInfo
    {
        public static string showName()
        { 
            return HttpContext.Current.Session["UserName"] ?? "";
        }
     }
  }

I know that this may have answered but I was not able to find the answer.


Solution

  • It will behave just fine. Yes, the class may be static but it will be accesing different sections of memory and no conflicts should arise from here.

    Internally, I believe, Session works exactly the same as Cache except for the fact that Session uses a unique Key (I believe is the current session Id) to store and retrieve the data from the dictionary. So when you store Session["Foo"]= "Bar" is really doing Session[session_id+"Foo"] = "Bar"

    Update

    My assumption is quasi confirmed:

    Comparing State Providers By default, ASP.NET applications store the session state in the memory of the worker process, specifically in a private slot of the Cache object. When the InProc mode is selected, the session state is stored in a slot within the Cache object. This slot is marked as private and is not programmatically accessible. Put another way, if you enumerate all the items in the ASP.NET data cache, no object will be returned that looks like the state of a given session. The Cache object provides for two types of slots—private and public. Programmers are allowed to add and manipulate public slots; the system, specifically classes defined in the system.web assembly, reserves for itself private slots. The state of each active session occupies a private slot in the cache. The slot is named after the session ID and the value is an instance of an internal, undocumented class named SessionStateItem. The InProc state provider takes the ID of the session and retrieves the corresponding element in the cache. The content of the SessionStateItem object is then poured into the HttpSessionState dictionary object and accessed by applications through the Session property. Notice that a bug in ASP.NET 1.0 makes private slots of the Cache object programmatically enumerable. If you run the following code under ASP.NET 1.0, you'll be able to enumerate items corresponding to objects packed with the state of each currently active session.

    Source: http://msdn.microsoft.com/en-us/library/aa479041.aspx

    (Apologies for the format. Posting from a cell phone)