17

I have a asp.net project with c# code behind. I have a static class called GlobalVariable where I store some information, like the currently selected product for example.

However, I saw that when there are two users using the website, if one changes the selected product, if changes it for everybody. The static variables seem to be commun to everybody.

I would want to create (from the c# code) some kind of session variable used only from the c# code, but not only from the page, but from any class.

Amaranth
  • 2,433
  • 6
  • 36
  • 58
  • Static variables are accessed throughout your application. Sessions are used to store & access variables within a user login & logout. Use a database to have your variables outlive your sessions and application. To share data between multiple applications use a distributed cache and store your [ASP.NET Session](http://www.alachisoft.com/ncache/session-index.html) in a cache. – Basit Anwer Dec 21 '15 at 07:52

3 Answers3

32

Yes static variables are shared by the whole application, they are in no way private to the user/session.

To access the Session object from a non-page class, you should use HttpContext.Current.Session.

driis
  • 161,458
  • 45
  • 265
  • 341
  • 3
    @Mathieu Remember to check for null, as Session will not always be created for every request. For example, simple handlers, like from .ashx files, are not setup by default to create the Session object. – Mike Guthrie Mar 08 '12 at 19:10
  • Apropos, http://stackoverflow.com/questions/1382791/asp-net-what-to-do-if-current-session-is-null/1382811#1382811 – driis Mar 08 '12 at 19:55
13

GlobalVariable is a misleading name. Whatever it's called, it shouldn't be static if it's per session. You can do something like this instead:

// store the selected product
this.Session["CurrentProductId"] = productId;

You shouldn't try to make the Session collection globally accessible either. Rather, pass only the data you need and get / set using Session where appropriate.

Here's an overview on working with session storage in ASP .NET on MSDN.

Yuck
  • 49,664
  • 13
  • 105
  • 135
11

You sort of answered your own question. An answer is in session variables. In your GlobalVariable class, you can place properties which are backed by session variables.

Example:

public string SelectedProductName 
{
    get { return (string)Session["SelectedProductName"]; }
    set { Session["SelectedProductName"] = value; }
}
Khan
  • 17,904
  • 5
  • 47
  • 59