如何阻止MVC缓存调用动作方法的结果?

时间:2010-06-03 20:18:07

标签: caching asp.net-mvc-2

我遇到了IE缓存操作方法结果的问题。

我发现的其他文章与安全性和[授权]属性有关。这个问题与安全性无关。

这是一个非常简单的“记录投票,抢平均值,返回平均值和投票数”的方法。关于它的唯一有趣的事情是它通过Ajax调用并返回一个Json对象。我相信它是被缓存的Json对象。

当我从FireFox运行它并使用Firebug观察XHR流量时,一切都运行良好。但是,在IE 8下,“throbber”图形没有时间显示,显示使用jQuery注入页面的“新”平均值和计数的页面元素永远不会有所不同。

我需要一种方法告诉M​​VC永远不要缓存此操作方法。

这篇文章似乎解决了这个问题,但我无法理解: Prevent Caching of Attributes in ASP.NET MVC, force Attribute Execution every time an Action is Executed

我需要更多上下文来解决方案,以了解如何扩展AuthorizationAttribute。请回答您的答案,就好像您正在与对MVC缺乏深刻理解的人交谈,即使这意味着回复了一篇关于某些必要基础/先决条件的文章。

谢谢,

Trey Carroll

1 个答案:

答案 0 :(得分: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()