I have a session variable that is set in my MVC application. Whenever that session expires and the user tries to refresh the page that they're on, the page will throw an error because the session is not set anymore.
Is there anywhere I can check to see if the session is set before loading a view? Perhaps putting something inside the Global.asax file?
I could do something like this at the beginning of EVERY ActionResult.
public ActionResult ViewRecord()
{
if (MyClass.SessionName == null)
{
return View("Home");
}
else
{
//do something with the session variable
}
}
Is there any alternative to doing this? What would the best practice be in this case?
If it's in one controller, you can do this:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
... // do your magic
}
It will fire before on any action execution. You can't return a view from there though, you'll have to redirect to anything that returns action result, e.g:
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Shared" }, { "action", "Home" } });
But, obviously, that should redirect to the action in the controller that's not affected by the override, otherwise you have a circular redirect. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With