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?

3
  • You're probably looking for HttpContext.Session Commented Jul 24, 2017 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. Commented Jul 24, 2017 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 Commented Jul 24, 2017 at 18:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you! yes that is what i was doing after realizing that the other approach is shared between all instances of the application.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.