MVC Equivalent of Page_Load

I have a session variable set in my MVC application. Whenever this session expires and the user tries to refresh the page on which they are located, the page throws an error because the session is no longer established.

Is there somewhere where I can check if a session is established before loading the view? Perhaps 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 an alternative to this? What would be the best practice in this case?

+6
source share
2 answers

First you have to redirect to Home, and not return Home View, otherwise you will have a strange situation with the home page, despite the fact that Url is somewhere else.

Secondly, Session will never be Null, because a new session is created when the old expires, or reset. Instead, you should check your variable, and if THAT is NULL, then you know there is a new session.

Thirdly, if the application depends on the session data, I would not use the session at all. Do you use this to cache data? If so, then using a cache might be the best choice (your application receives a notification when cache items expire).

Unfortunately, this is probably the case of Problem XY . You have a problem and you think that Session solves your problem, but you have another problem with Session, so you ask how to solve the session problem, and not how to solve the problem that 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 to the URL:

 http://website/Controller/ViewRecord/3 public ActionResult ViewRecord(int id) { // do whatever you need to do with the customer ID } 
0
source

If it is in one controller, you can do this:

 protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); ... // do your magic } 

It will fire before performing any action. However, you cannot return the view, you will have to redirect to everything that returns the result of the action, for example:

 filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Shared" }, { "action", "Home" } }); 

But obviously, this should be redirected to an action in the controller that does not affect the override, otherwise you have a circular redirect. :)

+3
source

Source: https://habr.com/ru/post/912857/


All Articles