在 ASP.NET MVC 中自动将用户重定向到登录页面而不是在页面上崩溃

To redirect the user to login page automatically instead of crash on page in ASP.NET MVC

在我们的 ASP.NET MVC 应用程序中,当会话超时时,页面会在我们有 Jquery AJAX 调用的组件上崩溃,但是如果我们手动加载页面,它会记录退出并重定向到登录页面。

我们希望用户在会话过期时自动重定向到登录页面,我们正在使用表单身份验证并定义了 CustomPrincipal。

global.asax

中插入以下代码
    public class SessionExpireAttribute : ActionFilterAttribute
    {
       public override void OnActionExecuting(ActionExecutingContext filterContext)
       {
          if (HttpContext.Current.Session["SessionId"] == null)
           {
            filterContext.Result = new RedirectResult("~/Home/Login");
            return;
        }
        base.OnActionExecuting(filterContext);
      }
    }

并且在每个控制器中调用这个属性如下

   [SolutionName.MvcApplication.SessionExpire]
   public class HomeController : Controller
   {
   }