4

Is there a simple way to redirect the entire page (not just the partial view) to the login page after the session has expired?

I have tried the following solutions, but can't get it to work:

My problem is that the partial view redirects to the Login-page, and not the entire page (same problem as in the links).

Controller

        [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);
        }

I wanted to return Redirect ("~/") if myID is null but it doesnt work since it expects a Partial View.

Error-message: Cannot implicitly convert type 'System.Web.Mvc.RedirectResult' to 'System.Web.Mvc.PartialViewResult'

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

    }

Picture of the view

Community
  • 1
  • 1
Erik Sellberg
  • 511
  • 1
  • 9
  • 23

2 Answers2

2

Web Config

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

Account Controller

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

_RedirectToLogin View

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

something like that, change the URLs accordingly

Emil
  • 281
  • 1
  • 2
  • 11
2

I'm going to build on @EmilChirambattu s answer.

[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 View

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

This should redirect you to the base URL of the page (most likely your login-page).

Danieboy
  • 4,393
  • 6
  • 32
  • 57