9

就像问题说的那样,我想知道是否可以关闭我整个站点的所有控制器和操作的缓存。谢谢!

4

4 回答 4

15

创建一个全局操作过滤器并覆盖OnResultExecuting()

public class DisableCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
    }
}

然后在你的 global.asax 中注册它,如下所示:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new DisableCache());
    }

总之,它的作用是创建一个全局动作过滤器,以便隐含地将其应用于所有控制器和所有动作。

于 2012-02-23T02:00:57.347 回答
5

您应该将此方法添加到您的 Global.asax.cs 文件中

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            Response.AddHeader("Pragma", "no-cache"); // HTTP 1.0.
            Response.AddHeader("Expires", "0"); // Proxies.
        }

这会禁用每个请求(图像、html、js 等)的缓存。

于 2013-05-27T08:14:40.563 回答
1

是的,取决于您采取的方法。我喜欢将动作应用到基本控制器(因此我在那里回复)。您可以在下面的链接中实现过滤器并将其实现为全局过滤器(在您的 global.asax.cs 中注册)

禁用整个 ASP.NET 网站的浏览器缓存

于 2012-02-23T01:59:59.137 回答
1

在 web.config 中,您可以添加额外的标头以与每个响应一起输出

<configuration>
    <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Cache-control" value="no-cache"/>
          </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>
于 2015-12-21T10:32:41.700 回答