There are numerous examples for the functionality that you want to achieve, but I wanted to give you a basic scenario of how you would do a redirect to the login page when a session expires or the user logs out:
Assuming you have setup your session, when a user will logout, the controller will have a Logout method:
public ActionResult Logout()
{
Session.Abandon();
Session.Clear();
return RedirectToAction("LoginPage", "Login");
}
This would destroy the session variables and redirect the user to the Login page.
Now when a session expires, you can do something like this:
public ActionResult SessionCheck()
{
string message = string.Empty;
if (Session["UserName"] == null)
{
message = "Session expired. Please Login again";
}
return Json(message, JsonRequestBehavior.AllowGet);
}
You can check for this method throughout your program using AJAX or you could use SessionState.
I prefer to use AJAX so I am giving you a simple example:
function IsSessionActive()
{
var url ="/Login/SessionCheck";
var param = {};
param = JSON.stringify(param);
var result = getResultPost(url, param);
if (result != "")
{
alert("Session has expired, Please login again");
//Redirect Here
window.location="@Url.Action("LoginPage", "Login")";
return true;
}
}
function getResultPost(url, param) {
var result;
$.ajax({
url: url,
type: "POST",
async: false,
dataType: "json",
data: param,
contentType: "application/json; charset=utf-8",
success: function (data, textStatus) {
result = data;
},
error: function (e) {
result = "Error";
}
});
return result;
}
And finally call this in your View like:
$(document).ready(function () {
if (IsSessionActive()) return false;
})
This will check for the session on every page that you call this method and if the session is expired, it will alert the user and redirect to the Login page. You can customize your own styles like a modal or customized alert box to show the user that their session has expired. I hope this helps.