【问题标题】:How to switch off caching for MVC requests but not for static files in IIS7?如何关闭 MVC 请求的缓存但不关闭 IIS7 中的静态文件?
【发布时间】:2011-05-03 22:37:44
【问题描述】:

我正在开发一个 ASP.NET MVC 应用程序。大多数控制器操作不应该被缓存。因此,我在Application_BeginRequest 中输出无缓存标头:

    protected void Application_BeginRequest()
    {
        HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
        HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
    }

应用程序在 IIS7 上运行,模块配置设置为 runAllManagedModulesForAllRequests="true"。这意味着所有静态文件也会通过请求管道(并禁用缓存)。

为这些静态文件启用缓存的最佳方法是什么?在Application_BeginRequest 中设置响应缓存标头之前是否必须检查扩展名,或者是否有更简单的方法(例如完全绕过静态文件的请求管道)?

【问题讨论】:

标签: c# .net asp.net-mvc caching iis


【解决方案1】:

假设您无法避免在 Hector 的链接中使用 runAllManagedModulesForAllRequests="true",您可以检查请求处理程序的类型,并仅在 MVC 处理请求时设置缓存标头。

protected void Application_PreRequestHandlerExecute()
{
    if ( HttpContext.Current.CurrentHandler is MvcHandler )
    {
        HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
        HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
    }
}

请注意,我已将代码移至Application_PreRequestHandlerExecute,因为尚未在BeginRequest 中选择处理程序,因此HttpContext.Current.CurrentHandler 为空。

【讨论】:

  • 这很好用。它还允许您在 else 语句中为静态文件设置自定义缓存控制。
【解决方案2】:

您可以拥有一个缓存过滤器属性,将其应用于您的所有操作(通过基本控制器或在每个控制器或操作上显式)。这不适用于您的静态文件。

可能的[CacheFilter]:

using System;
using System.Web;
using System.Web.Mvc;

    public class CacheFilterAttribute : ActionFilterAttribute
    {

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

            cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            cache.SetValidUntilExpires(false);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetNoStore();
        }
    }

顺便说一句,您甚至可以从不同的域交付您的静态文件,就像使用 sstatic.net 一样,这将消除您的问题作为副作用。

【讨论】:

    猜你喜欢
    • 2012-03-30
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2011-06-15
    相关资源
    最近更新 更多