1

I'm working in an MVC application using MVC5. I was wondering about how can I declare a global variable. I have created variables in global.asax like this:

HttpContext.Current.Application["Login"] = "Jonh Doe";

Also I have created private static members in the controllers. But I have realized that if two users are browsing the app the value that one store on the variable is shared between the rest.

Any way that i can store variables that are not shared between all instances of the application?

  • You're probably looking for [`HttpContext.Session`](https://msdn.microsoft.com/en-us/library/system.web.httpcontext.session%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) – Scott Jul 24 '17 at 18:44
  • So the only way is to store it on the session? at the end that is what i have ended doing it. but not like you explain, your example is better. – Sergio Cabrera Gari Jul 24 '17 at 18:49
  • i have created on the controller this structure public string facilitySelected { get { return Session["Facility"].ToString(); } set { Session["Facility"] = value; } } thank you – Sergio Cabrera Gari Jul 24 '17 at 18:50

1 Answers1

1

Yes, you can use session, which is global to the current user only:

HttpContext.Current.Session["Login"] = "John Doe";

However, you won't do that in global.asax because Session is a module that gets initialized at a very specific time (see this). As such, you most likely want to do it in the controller at an appropriate time:

public ActionResult Index()
{
   this.HttpContext.Session["Login"] = "X";
}

As an oversimplified example.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257