Page_Load中的MVC等效 [英] MVC Equivalent of Page_Load

查看:193
本文介绍了Page_Load中的MVC等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在我的MVC应用程序设置会话变量。每当会话过期和用户尝试刷新他们的网页,因为会话未设置了页面会抛出一个错误。

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.

在哪里有,我可以检查是否会话加载视图之前设置?也许把东西Global.asax文件里面呢?

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?

我可以在每一个的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?

推荐答案

首先,你应该重定向到主页,不能返回首页查看,否则,您必须显示出来,尽管URL为其他地方的主页的怪异局面。

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

不幸的是,这可能是的XY问题的情况。你有一个问题,您认为会议解决您的问题,但你运行到一个不同的问题与会议,所以你问如何,而不是如何解决这个问题会话正在设法解决解决您的会话的问题。

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?

编辑:

根据您的评论如下,你为什么不通过对URL的客户编号:

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
} 

这篇关于Page_Load中的MVC等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆