Search code examples
c#ajaxasp.net-mvcaction-filter

ActionFilter is not working with AJAX call


I have an AJAX call for a DataTable that is calling a method in my controller with a return type of JsonResult. If the user's session has expired, I get a JSON error alert and the site hangs. I am trying to use an ActionFilter to check if the user's session has expired before processing the request. It works when the method return type is ActionResult. However, when the return type is JsonResult, I see the error and it hangs. When tracing, I see that the ActionFilter is being called and the code works fine, but it will not redirect the user to the login page like it should. Is there a way to abort the AJAX call server-side and redirect the user as intended?

Action Filter

public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
            if (ctx.Session != null)
            {
                if (ctx.Session.IsNewSession)
                {
                    string cookieHeaders = ctx.Request.Headers["Cookie"];

                    if ((null != cookieHeaders) && (cookieHeaders.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        filterContext.Result = new RedirectResult("~/Account/Login");
                        return;
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }

Solution

  • We can check if request is Ajax then return json result and on the client side check if server returned error redirect to login page like:

    if ((null != cookieHeaders) && (cookieHeaders.IndexOf("ASP.NET_SessionId") >= 0))
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
                
              filterContext.Result = new JsonResult
              {
                  Data = new {Error = "UnAutorized", Url = Url.Action("Login","Account")},
                  JsonRequestBehavior = JsonRequestBehavior.AllowGet
              };
    
              return;
         }
         else
         {
             filterContext.Result = new RedirectResult("~/Account/Login");
             return;
         }
    }
    

    Now for normal request it will redirect to login page and for ajax call will reutrn json response with unauthorized error message and url where should be redirected and on client side we can then redirect like:

    window.location.href = response.Url;