在不使用get,post或cookie的情况下在会话之间保存数据

时间:2013-02-18 20:14:06

标签: asp.net-mvc asp.net-mvc-3

我有一个带有两个动作功能的控制器类。一个操作是我的登录页面有一个视图,另一个是我的后端页面有多个视图。

public ActionResult Login(...)
{
    if (logged in or login success)
    {
        return RedirectToAction("Backend","Controller");
    }
    ...
    return View();
}

public ActionResult Backend(...)
{
    if(session expired or not logged in)
    {
        return RedirectToAction("Login","Controller");
    }
    ...
    return View("someView");
}

问题是后端操作必须将用户发送到登录操作,并且我想在登录页面上向用户显示“Session expired”之类的消息。

作为示例,ViewBag仅存在于当前会话中。但有没有类似的简单方法在会话之间存储信息?所以我可以在后端设置一条消息,然后重定向到登录,并让登录读取该消息并在视图中显示它?有点像PersistentViewBag。

我真的不想使用get,post或cookies,因为这是一个可行的选择,但我宁愿在后端操作中将登录作为自己的视图。

1 个答案:

答案 0 :(得分:2)

当您重定向到登录页面时,您可以简单地使用查询字符串来传递数据。

public ActionResult Backend(...)
{
    if(session expired or not logged in)
    {
        return RedirectToAction("Login","Controller",new { IsSessionExpired = true });
    }
    ...
    return View("someView");
}

在“登录”操作中,您可以检查查询字符串并确定是否要显示该消息。

<强>更新

如果您不想使用查询字符串,也可以使用TempData。

public ActionResult Backend(...)
{
    if(session expired or not logged in)
    {
        TempData["IsSessionExpired"] = true;
        return RedirectToAction("Login","Controller");
    }
    ...
    return View("someView");
}

然后你可以在登录操作中检查它:

if(TempData["IsSessionExpired"] != null)
{
    //Show message
}
相关问题