I am not sure I am asking the right question here.
I have a shared page (master page) that calls a couple of partial pages for side menu, header, footer etc.. and all my controllers inherit a BaseController.
Now, depending on the user login status, I need to show different data in all those partial pages and I thought where is the best place to check whether a user is logged in or not – BaseController.
And therein lies my problem. I need to contact one of my web services to see if a user is logged in and get some relevant data if he is. I only need to do this once, and since all controllers inherit from BaseController, each of those partial page calls results in the web service call.
Obviously, I cannot just stick a private bool variable isUserAuthenticated and check for flag, as, each controller will have a new instance of the base controller.
In traditional asp.net projects, I would put this stuff in HttpContext.Current.Items[] and use re-use it but I cannot (somehow) access that in MVC.
I cannot just not inherit from basepage on partial pages as they can also be called independently and I need to know the user login status then too.
What is the best way to call a function just once, or, rather, store a bool value for the duration of one call only? – accessible between controlers..
How do people do this?
thanks, sorry, I’m a newbie to mvc!
You can still use
HttpContext.Items, but you’ll need to access it via aHttpContextBaseinstance.For backwards compatibility you can wrap an
HttpContextin anHttpContextWrapper, like so@iamserious’s answer above suggests using a static property – which I strongly disagree with. Setting a static variable is application wide and would mean each and every user would be using the same variable – so all would have the same login data. You want to store it either per user in
Sessionor perRequestviaHttpContext.Items.I’d suggest doing something using like this approach, then no matter where you call ContextStash.GetInstance, you’ll receive the same instance for the lifetime of the same request. You could also follow the same pattern and use
HttpContext.Sessioninstead ofHttpContext.Items: