I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.
In short, I catch session end in _Layout 1 minute before and make redirection.
I try to explain everything step by step.
If we want to session end 30 minute after and redirect to loginPage see this steps:
Change the web config like this (set 31 minute):
<system.web>
<sessionState timeout="31"></sessionState>
</system.web>
Add this JavaScript in _Layout
(when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)
<script>
//session end
var sessionTimeoutWarning = @Session.Timeout- 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location = "/Account/LogOff";
}
</script>
Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page
public ActionResult LogOff()
{
Session["User"] = null; //it's my session variable
Session.Clear();
Session.Abandon();
FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
return RedirectToAction("Login", "Account");
}
I hope this is a very useful code for you.