Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net MVC Partial View load login page when session expires

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

like image 994
yohan.jayarathna Avatar asked Mar 21 '14 08:03

yohan.jayarathna


2 Answers

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>
like image 196
kramwens Avatar answered Nov 18 '22 08:11

kramwens


The issue is your call is intercepted by [Authorize] and sends the login page even before your action method code is called. One way to sort this out is to create a custom action filter to check the timeout and do a hard redirect to login page. Following post has a good write up which may help you in creating and registering the filter

http://www.codeblockdrive.com/2012/12/mvc-custom-filters-session-timeout.html

Best of luck

like image 22
Chintana Meegamarachchi Avatar answered Nov 18 '22 09:11

Chintana Meegamarachchi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!