首頁  >  文章  >  後端開發  >  實作超時彈跳窗後跳轉功能的asp程式碼實例

實作超時彈跳窗後跳轉功能的asp程式碼實例

Y2J
Y2J原創
2017-05-04 11:01:531546瀏覽

這篇文章主要介紹了Asp.net 中mvc 實現超時彈跳窗後跳轉功能,非常不錯,具有參考借鑒價值,需要的朋友可以參考下

為了實現保持登入狀態,可以用cookie來解決這一問題

假設過期時間為30分鐘,校驗發生在伺服器,借助過濾器,可以這樣寫

 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);
      }
    }
  }

但是頁面直接跳轉了,也沒有一個提示,顯得不是很友好,可以這樣

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(&#39;登录超时,请重新登录&#39;);location.href=&#39;{0}&#39;</script>","/admin/login/index")
        };
      }
      else
      {
        cookie.Expires = DateTime.Now.AddMinutes(30);
        HttpContext.Current.Response.Cookies.Remove("loginInfo");
        HttpContext.Current.Response.Cookies.Add(cookie);
      }
    }
  }
}

但是,假如是ajax請求呢?

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(&#39;登录超时,请重新登录&#39;);location.href=&#39;{0}&#39;</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);
      }
    }
  }

以上是實作超時彈跳窗後跳轉功能的asp程式碼實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn