2010-06-03 77 views
6

我遇到IE高速緩存操作方法結果的問題。如何停止MVC緩存調用操作方法的結果?

我發現的其他文章與安全性和[Authorize]屬性有關。這個問題與安全無關。

這是一個非常簡單的「記錄投票,搶平均,返回平均數和投票數」的方法。唯一有趣的是它通過Ajax調用並返回一個Json對象。我相信這是獲得緩存的Json對象。

當我從FireFox運行它並用Firebug觀看XHR流量時,一切都很完美。然而,在IE 8下,「throbber」圖形從來沒有時間顯示出來,顯示用jQuery注入頁面的「new」avg和count的頁面元素從來不會有所不同。

我需要一種方法來告訴MVC從不緩存這個操作方法。

這篇文章似乎爲解決這個問題,但我不明白: Prevent Caching of Attributes in ASP.NET MVC, force Attribute Execution every time an Action is Executed

我需要更多的上下文解決了解如何擴展AuthorizationAttribute。請給出你的答案,就好像你在和一個對MVC沒有深入理解的人說話,即使這意味着回覆一篇關於必需的基礎知識/先決條件的文章。

感謝,

崔卡羅爾

回答

21

MVC不緩存的結果。 IE確實。

所以你必須告訴IE不要這樣做。

下面是我如何做到這一點。首先,屬性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 
public sealed class CacheControlAttribute : ActionFilterAttribute 
{ 
    public CacheControlAttribute(HttpCacheability cacheability) 
    { 
     this._cacheability = cacheability; 
    } 

    public HttpCacheability Cacheability { get { return this._cacheability; } } 

    private HttpCacheability _cacheability; 

    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache; 
     cache.SetCacheability(_cacheability); 
    } 
} 

接下來,一個動作:

[CacheControl(HttpCacheability.NoCache), HttpGet] 
    public JsonResult MyAction() 
+0

謝謝克雷格。這正是我需要的。我只是將該類添加到MVC項目的根級別,但是,我相信這是不正確的。在MVC 2解決方案中,這個類的正確位置是什麼? – 2010-06-10 03:59:29

+0

由你決定。這實際上是框架代碼。您可以將它放在單獨的類庫或Web應用程序中的「Mvc」命名空間中。 – 2010-06-10 12:07:11

+3

這是MVC簡單得多現在,只要使用的OutputCache並設置持續時間爲0秒: [的OutputCache(持續時間= 0)] 公共的ActionResult城市(INT provinceId){ VAR myData的= SomeClassInstance.SomeMethod(); return Json(myData,JsonRequestBehavior.AllowGet); } – 2012-05-03 16:00:22