2012-08-24 47 views
3

我已經閱讀了大量有關類似問題但未找到工作解決方案的帖子。我有一個MVC 4網站,我不想從整個網站中刪除緩存,因爲我想緩存頁面。當用戶單擊註銷按鈕時,它會成功註銷並重定向到登錄頁面,但是當用戶單擊後退按鈕時,它會顯示以前查看過的「受限制頁面」,您應該只能看到它是否已登錄。我明白這是因爲瀏覽器已經緩存了頁面客戶端。我已經嘗試了很多解決方案,正如前面提到的,他們都沒有工作。目前我註銷具有下面的代碼:MVC 4 - 註銷後的後退按鈕問題

public ActionResult LogOff() 
    { 

     FormsAuthentication.SignOut(); 
     Session.Abandon(); 
     Session.Clear(); 

     // clear authentication cookie 
     HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, ""); 
     cookie1.Expires = DateTime.Now.AddYears(-1); 
     Response.Cookies.Add(cookie1); 

     // clear session cookie (not necessary for your current problem but i would recommend you do it anyway) 
     HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", ""); 
     cookie2.Expires = DateTime.Now.AddYears(-1); 
     Response.Cookies.Add(cookie2); 

     // Invalidate the Cache on the Client Side 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); 
     Response.Cache.SetNoStore(); 

     Response.AppendHeader("Pragma", "no-cache"); 

     // send an expired cookie back to the browser 
     var ticketExpiration = DateTime.Now.AddDays(-7); 
     var ticket = new FormsAuthenticationTicket(
      1, 
      // replace with username if this is the wrong cookie name 
      FormsAuthentication.FormsCookieName, 
      DateTime.Now, 
      ticketExpiration, 
      false, 
      String.Empty); 
     var cookie = new System.Web.HttpCookie("user") 
     { 
      Expires = ticketExpiration, 
      Value = FormsAuthentication.Encrypt(ticket), 
      HttpOnly = true 
     }; 

     Response.Cookies.Add(cookie); 

     return RedirectToAction("Login", "Account"); 
    } 
+0

我不知道你是如何做你的認證。但是不應該每個網站都檢查你的數據庫以確保用戶在網站上有適當的身份驗證嗎?如果沒有,它應該重新引導他展示一些東西。即使您的頁面被緩存,您的腳本仍會運行,並且存儲在數據庫中的用戶會話應顯示他已註銷。 – AwDogsGo2Heaven

+0

當然,它不會起作用,您的到期代碼隻影響* current *請求是否被緩存。當前請求是您的註銷代碼,因此只有註銷頁面纔會被解除緩存。緩存後的頁面不能追溯刪除。 –

回答

0

您可以使用瀏覽器窗口中的散列變化事件,觸發回發一個Ajax請求,這顯然會失敗,因爲你的退出。從那裏你可以觸發瀏覽器做你喜歡的任何事情。

4

如果您想要在所有頁面上應用「無緩存回瀏覽器」行爲,那麼您應該將以下內容放在global.asax中。

protected void Application_BeginRequest() 
{ 
    Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1)); 
    Response.Cache.SetNoStore(); 
} 

希望它可以幫助別人!

0

將以下代碼行添加到Global.asax.cs文件中。

protected void Application_BeginRequest() 
{ 
    Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1)); 
    Response.Cache.SetNoStore(); 
}