What you will need to do involves some server side and client side coding.
Firstly on the server side you will need to capture requests where the users session has expeired AND they are using ajax.
If you are using the standard Authentication attribute you can extend it like this:
public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
private class Http401Result : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 401;
context.HttpContext.Response.Write("Your session has expired. Please login again to continue.");
context.HttpContext.Response.End();
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new Http401Result();
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
Use that attribute instead of Authorize
on your Controller or Action.
Now to the client side, when a request comes back from the server with a 401 response you want to capture it and do something, lets use a Ajax Setup for this:
Stick this someone it will always run:
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$(document).ajaxError(
function (e, request) {
if (request.status == 401) {
alert("Your session has expired. Please login again to continue.");
window.location = "/account/logon";
} else {
}
}
);
}
And youre done.