会话到期时将部分视图重定向到登录页面

时间:2016-07-20 07:39:08

标签: asp.net asp.net-mvc session asp.net-mvc-partialview

会话过期后,是否有一种简单的方法可以将整个页面(不仅仅是部分视图)重定向到登录页面?

我尝试了以下解决方案,但无法让它发挥作用:

我的问题是局部视图重定向到登录页面,而不是整个页面(与链接中的问题相同)。

控制器

        [HttpPost]
        public PartialViewResult LogPartialView(string a, int? b, string c, string d, int? e, string f)
        {
            //If the user is "Admin" -> display Logs for all customers.
            if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
            {
                if (Session["myID"] == null)
                {
                    ExpireSession();
                }
            //Some code

        return PartialView("LogPartialLayout", model);
        }

如果myID为null,我想返回Redirect("〜/")但它不起作用,因为它需要一个部分视图。

错误消息:无法隐式转换类型' System.Web.Mvc.RedirectResult' to' System.Web.Mvc.PartialViewResult'

public void ExpireSession()
    {
        Session.Abandon();
        WebSecurity.Logout();
        Response.Redirect("~/");

    }

Picture of the view

2 个答案:

答案 0 :(得分:2)

Web Config

<authentication mode="Forms">
  <forms loginUrl="~/Account/RedirectToLogin" timeout="2880" />
</authentication>

帐户控制器

public ActionResult RedirectToLogin()
{
    return PartialView("_RedirectToLogin");
}

_RedirectToLogin查看

<script>
    window.location = '@Url.Action("Login", "Account")';
</script>

类似的东西,相应地更改URL

答案 1 :(得分:2)

我将以@EmilChirambattu的回答为基础。

[HttpPost]
public ActionResult LogPartialView(string a, int? b, string c, string d, int? e, string f)
{
    // You should check the session before anything else.
    if (Session["myID"] == null)
    {
        return ExpireSession();
    }

    //If the user is "Admin" -> display Logs for all customers.
    if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
    {
        //Some code
    }

    return PartialView("LogPartialLayout", model);
}

public void ExpireSession()
{
    Session.Abandon();
    WebSecurity.Logout();
    Response.Redirect("RedirectToLogin");
}

public ActionResult RedirectToLogin()
{
    return PartialView("_RedirectToLogin");
}

_RedirectToLogin查看

<script>
    window.location = '@Url.Action("Index", "")';
</script>

这应该会将您重定向到页面的基本URL(很可能是您的登录页面)。