加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC捆绑客户端缓存

发布时间:2020-12-15 18:52:53 所属栏目:asp.Net 来源:网络整理
导读:默认情况下,一个MVC包在客户端上缓存1年。是否可以手动设置它的客户端头(对于1特定的包)? 我需要的是为我的一个包设置自定义过期标头。我不能依赖“v = hash”查询字符串,因为这个包是一个外部网站,并且他们不会改变指向我的包的URL每次我更改它。 我试
默认情况下,一个MVC包在客户端上缓存1年。是否可以手动设置它的客户端头(对于1特定的包)?

我需要的是为我的一个包设置自定义过期标头。我不能依赖“v = hash”查询字符串,因为这个包是一个外部网站,并且他们不会改变指向我的包的URL每次我更改它。

我试过的是创建一个自定义Bundle类(继承Bundle)和覆盖GenerateBundleResponse()方法。这样我可以控制服务器缓存,但定制客户端缓存的唯一方法是设置BundleResponse.Cacheability(public,private,nocache等)。但我不能手动设置标头。我可以访问BundleContext(和它的HttpContext),但是当我设置头文件上下文,它将影响所有其他请求以及。

解决方法

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

注意: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);
    }
}

在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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读