mvc in Asp. net realizes jump function after timeout pop up window

  • 2021-09-11 19:55:46
  • OfStack

In order to maintain login status, cookie can be used to solve this 1 problem

Assuming that the expiration time is 30 minutes and the verification occurs on the server, with the help of a filter, you can write this


 public class PowerFilter : AuthorizeAttribute
  {
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      var cookie = HttpContext.Current.Request.Cookies["loginInfo"];
      if(null == cookie)
      {
        filterContext.Result = new RedirectResult("/admin/login/index");
      }
      else
      {
        cookie.Expires = DateTime.Now.AddMinutes(30);
        HttpContext.Current.Response.Cookies.Remove("loginInfo");
        HttpContext.Current.Response.Cookies.Add(cookie);
      }
    }
  }

However, the page jumped directly, and there was no hint, which was not very friendly. It can be like this


public class PowerFilter : AuthorizeAttribute
  {
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      var cookie = HttpContext.Current.Request.Cookies["loginInfo"];
      if(null == cookie)
      {
        filterContext.Result = new ContentResult()
        {
          Content = string
          .Format("<script>alert(' Login timeout , Please log in again ');location.href='{0}'</script>","/admin/login/index")
        };
      }
      else
      {
        cookie.Expires = DateTime.Now.AddMinutes(30);
        HttpContext.Current.Response.Cookies.Remove("loginInfo");
        HttpContext.Current.Response.Cookies.Add(cookie);
      }
    }
  }
}

But what if it is an ajax request?


public class PowerFilter : AuthorizeAttribute
  {
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      var cookie = HttpContext.Current.Request.Cookies["loginInfo"];
      if(null == cookie)
      {
        if(!filterContext.HttpContext.Request.IsAjaxRequest())
        {
          filterContext.Result = new ContentResult()
          {
            Content = string
                 .Format("<script>alert(' Login timeout , Please log in again ');location.href='{0}'</script>","/admin/login/index")
          };
        }
        else
        {
          filterContext.Result = new JsonResult()
          {
            Data = new { logoff = true,logurl = "/admin/login/index" },
            ContentType = null,
            ContentEncoding = null,
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
          };
        }
      }
      else
      {
        cookie.Expires = DateTime.Now.AddMinutes(30);
        HttpContext.Current.Response.Cookies.Remove("loginInfo");
        HttpContext.Current.Response.Cookies.Add(cookie);
      }
    }
  }

Related articles: