這篇文章主要介紹了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('登录超时,请重新登录');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); } } } }
但是,假如是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('登录超时,请重新登录');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); } } }
以上是實作超時彈跳窗後跳轉功能的asp程式碼實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!