MVC捆绑客户端缓存

sti*_*net 28 asp.net-mvc resourcebundle asp.net-mvc-4

默认情况下,MVC包在客户端上缓存1年.是否可以手动设置它的客户端头(针对1个特定的捆绑包)?

我需要的是为我的一个捆绑包设置自定义过期标头.我不能依赖"v = hash"查询字符串,因为这个包是用于外部网站的,每次我更改时它们都不会更改指向我的包的网址.

我试过的是创建一个自定义的Bundle类(继承Bundle)并覆盖GenerateBundleResponse()方法.这样我可以控制服务器缓存,但自定义客户端缓存的唯一方法是设置BundleResponse.Cacheability(public,private,nocache等).但我无法手动设置标头.我可以访问BundleContext(它是HttpContext),但是当我在该上下文中设置标题时,它也会对所有其他请求产生影响.

Kam*_*him 11

不幸的是没有办法.您可以在捆绑的内部实现中找到原因.在BundleHandler类ProcessRequest中调用类的ProcessRequest内部方法,Bundle并在它之前调用SetHeaders HttpContext.Response.Write.因此,客户端缓存在响应写入之前设置为一年.

注意:BundleHandler是内部密封类: internal sealed class BundleHandler : IHttpHandler

BundleHandler课堂上:

public void ProcessRequest(HttpContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    }
    context.Response.Clear();
    BundleContext context2 = new BundleContext(new HttpContextWrapper(context), BundleTable.Bundles, this.BundleVirtualPath);
    if (!Bundle.GetInstrumentationMode(context2.HttpContext) && !string.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"]))
    {
        context.Response.StatusCode = 304;
    }
    else
    {
        this.RequestBundle.ProcessRequest(context2);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bundle课堂上:

internal void ProcessRequest(BundleContext context)
{
    context.EnableInstrumentation = GetInstrumentationMode(context.HttpContext);
    BundleResponse bundleResponse = this.GetBundleResponse(context);
    SetHeaders(bundleResponse, context);
    context.HttpContext.Response.Write(bundleResponse.Content);
}

private static void SetHeaders(BundleResponse bundle, BundleContext context)
{
    if (bundle.ContentType != null)
    {
        context.HttpContext.Response.ContentType = bundle.ContentType;
    }
    if (!context.EnableInstrumentation)
    {
        HttpCachePolicyBase cache = context.HttpContext.Response.Cache;
        cache.SetCacheability(bundle.Cacheability);
        cache.SetOmitVaryStar(true);
        cache.SetExpires(DateTime.Now.AddYears(1));
        cache.SetValidUntilExpires(true);
        cache.SetLastModified(DateTime.Now);
        cache.VaryByHeaders["User-Agent"] = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请参阅stackoverflow.com/a/34508048/1545567以解决该问题并完全控制缓存持续时间 (2认同)