2011-03-18 229 views
9

我需要過期我的內容,以便當用戶點擊瀏覽器導航(後退)按鈕控制器動作得到執行。因此,不要將以下代碼添加到每個動作中,還是有更好的方法來實現它。MVC3剃刀 - 過期頁面

HttpContext.Response.Expires = -1; 
HttpContext.Response.Cache.SetNoServerCaching(); 
Response.Cache.SetAllowResponseInBrowserHistory(false); 
Response.CacheControl = "no-cache"; 
Response.Cache.SetNoStore(); 

回答

27

你可以把這個邏輯放到一個ActionFilter也就是說,而不是添加上面的代碼到你的每一個動作方法,你的控制器,你可以裝點您的自定義過濾器的操作方法。或者,如果它適用於Controller中的所有Action方法,則可以將該屬性應用於整個Controller。

你ActionFilter會是這樣的:

public class MyExpirePageActionFilterAttribute : System.Web.Mvc.ActionFilterAttribute 
    { 
     public override void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext) 
     { 
      base.OnActionExecuted(filterContext); 

      filterContext.HttpContext.Response.Expires = -1; 
      filterContext.HttpContext.Response.Cache.SetNoServerCaching(); 
      filterContext.HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false); 
      filterContext.HttpContext.Response.CacheControl = "no-cache"; 
      filterContext.HttpContext.Response.Cache.SetNoStore(); 

     } 
    } 

this文章以獲取更多信息。

如果你想這對整個應用程序的所有操作,實際上你可以申請一個ActionFilter使用全球ActionFilter在Global.asax中設立的所有操作:

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 

    GlobalFilters.Filters.Add(new MyExpirePageActionFilterAttribute()); 

    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 
} 
+0

是的我同意我需要創建一個ActionFilter。我正在創建這個過程。所以我想這種方法是根據你的反應進行驗證的。我想要的反饋是在過濾器內部。我覺得這5條線是否合理?還是有更好的方法去做?謝謝。 – kolhapuri 2011-03-18 15:03:33

+0

@kolhapuri我看,看看這個[鏈接這裏](http://stackoverflow.com/questions/1906163/how-to-force-a-page-refresh-while-pressing-the-back-button-in- mac-safari),它描述了某人希望阻止Safari緩存前一頁。 – Swaff 2011-03-18 15:13:48

+0

今天遇到了這個問題,它解決了我遇到的問題! – 2012-08-06 20:30:55