【问题标题】:How do I turn off caching for my entire ASP.NET MVC 3 website?如何关闭整个 ASP.NET MVC 3 网站的缓存?
【发布时间】:2012-03-13 10:37:03
【问题描述】:

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

【问题讨论】:

    标签: asp.net-mvc-3 caching output-caching


    【解决方案1】:

    创建一个全局操作过滤器并覆盖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,以便隐含地将其应用于所有控制器和所有操作。

    【讨论】:

    • 感谢您的回复。脚本、图像和 CSS 怎么样?全局操作过滤器也会影响这些吗?换句话说,动作过滤器是否仅在对控制器/动作的请求或每个请求时才被调用?就像@AdamTuliper 提到的那样,我不想缓存那些
    • @enamrik 嗯……经过测试,看起来图像和 css 仍然使用这个全局操作过滤器缓存。我必须研究如何防止这种情况发生。
    • 没关系,显然这就是动作过滤器的定义,它们只在对动作的请求时运行
    • @enamrik 对,没错。也许这是需要在客户端处理的事情..?
    • 好吧,我并不真正关心脚本、图像和 css 是否被缓存。我有点没有时间深入研究这个问题,但是如果到了我不想缓存我的脚本图像和 css(敏感徽标?)的时候,我会问另一个问题,:-)。谢谢!
    【解决方案2】:

    您应该将此方法添加到您的 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 等)的缓存。

    【讨论】:

      【解决方案3】:

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

      Disable browser cache for entire ASP.NET website

      【讨论】:

        【解决方案4】:

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

        <configuration>
            <system.webServer>
                <httpProtocol>
                  <customHeaders>
                    <add name="Cache-control" value="no-cache"/>
                  </customHeaders>
                </httpProtocol>
            </system.webServer>
        </configuration>
        

        【讨论】:

          猜你喜欢
          • 2011-08-17
          • 2011-07-28
          • 1970-01-01
          • 2010-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-14
          相关资源
          最近更新 更多