MVC Equivalent of Page_Load

回眸只為那壹抹淺笑 提交于 2019-12-23 09:34:23

问题


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?


回答1:


First, you should redirect to Home, not return the Home View, otherwise you have the weird situation of the home page showing up despite the Url being somewhere else.

Second, Session will never be Null, because a new session gets created when the old one expires or is reset. You would instead check for your variable and if THAT is null, then you know the session is new.

Third, If you app depends on this session data, then I would not use a session at all. Are you using this to cache data? If so, then using Cache may be a better choice (your app gets notified when cache items expire).

Unfortunately, this is probably a case of The XY Problem. You have a problem, and you believe Session solves your problem, but you're running into a different problem with Session, so you are asking how to solve your session problem rather than how to solve the problem Session is trying to solve.

What is the real problem you are trying to solve with this?

EDIT:

Based on your comment below, why don't you pass the customer number on the url:

http://website/Controller/ViewRecord/3

public ActionResult ViewRecord(int id) 
{ 
    // do whatever you need to do with the customer ID
} 



回答2:


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. :)



来源:https://stackoverflow.com/questions/10090934/mvc-equivalent-of-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!