.Net MVC Partial View load login page when session expires

yohan.jayarathna picture yohan.jayarathna · Mar 21, 2014 · Viewed 8.3k times · Source

I am building a web application using .net MVC 4.

I have ajax form to edit data.

enter image description here

If the user is idle for 15 mins it will expire the session of the user. When that happens if user click edit button it loads the login page inside the partial content hence now the current session expires.

enter image description here

Edit Link - cshtml code

@Ajax.ActionLink("Edit", MVC.Admin.Material.ActionNames.TagEditorPanel, MVC.Admin.Material.Name, new { isView = "false", id = Model.ID.ToString() }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "materialTagBox", InsertionMode = InsertionMode.Replace }, new { @class = "editlinks" })

Controller/Action Code

[Authorize]
public virtual ActionResult TagEditorPanel(bool isView, int id)
{
   //do something
   return PartialView(MVC.Admin.Material.Views._tag, response);
}

Web.config

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

I understand why it is happening. I don't know how to resolve it. I want to prevent it and I want to redirect user to login page directly. How can I achieve this?

Thanks inadvance..!!!

Answer

kramwens picture kramwens · May 29, 2014

Maybe a hacky answer, but you can change the redirect location in forms authentication to a page that sets the window location to the login page with javascript.

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>