【发布时间】:2012-03-13 10:37:03
【问题描述】:
就像问题所说的那样,我想知道是否可以关闭我整个网站的所有控制器和操作的缓存。谢谢!
【问题讨论】:
标签: asp.net-mvc-3 caching output-caching
就像问题所说的那样,我想知道是否可以关闭我整个网站的所有控制器和操作的缓存。谢谢!
【问题讨论】:
标签: asp.net-mvc-3 caching output-caching
创建一个全局操作过滤器并覆盖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());
}
总而言之,它的作用是创建一个Global Action Filter,以便隐含地将其应用于所有控制器和所有操作。
【讨论】:
您应该将此方法添加到您的 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 等)的缓存。
【讨论】:
是的,取决于您采用的方法。 我喜欢将动作应用到基本控制器(因此我在那里回复)。您可以在下面的链接中实现过滤器并将其实现为全局过滤器(在您的 global.asax.cs 中注册)
【讨论】:
在 web.config 中,您可以添加额外的标头以与每个响应一起输出
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Cache-control" value="no-cache"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
【讨论】: