I have a ASP MVC page where when the session is expired needs to redirect to login page. If the user is in a page and session expires and if the user refresh the page, the user gets redirected to login page. However, if the user clicks on button, the page never redirects to login page. I have a custom ActionFilter within each controller action method to check for session and i am using 'RedirectToRouteResult' object to redirect the page, however it only seems to work if the user refreshes the page but not when the button gets clicked.
Here is my custom action filter:
public class CustomCheckSessionOutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim();
//Check Start with
if (!actionName.StartsWith("Login") && !actionName.StartsWith("LogOff"))
{
var session = HttpContext.Current.Session["LoggedInUserInfo"];
//Redirects user to login screen if session has timed out
if (session == null)
{
base.OnActionExecuting(filterContext);
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Account",
action = "Login",
returnUrl = ((HttpRequestWrapper)((HttpContextWrapper)filterContext.HttpContext).Request).Url
}));
}
}
}
}
Here is the sample of action method in Controller:
[Authorize(Roles = "Client")]
[CustomCheckSessionOut]
public ActionResult GetOrders([DataSourceRequest] DataSourceRequest request, string orderId)
{
}
Any suggestion how i can redirect user to login page if session is expired and if the button is clicked? Thanks.
UPDATE: Thanks to Fabien, i used his approach to get it resolved like this:
Global.asax.cs
protected void Application_EndRequest()
{
var context = new HttpContextWrapper(Context);
// If we're an ajax request, and doing a 302, then we actually need to do a 401
if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
{
Context.Response.Clear();
Context.Response.StatusCode = 401;
Context.Response.StatusDescription = "expiredSession";
}
}
Javascript:
$(document).ajaxComplete(function (e, xhr, options) {
if (xhr != null) {
if (xhr.getResponseHeader('X-Responded-JSON') != null) {
var responseHeader = jQuery.parseJSON(xhr.getResponseHeader('X-Responded-JSON'));
if (responseHeader.status === 401) {
e.stopPropagation();
window.location.href = responseHeader.headers.location;
}
}
if (xhr.status === 401 && xhr.statusText === "expiredSession") {
// Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
e.stopPropagation();
location.reload();
}
}
});