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

caching – MVC4 StyleBundle:你能在Debug模式下添加一个缓存清

发布时间:2020-12-15 19:22:16 所属栏目:asp.Net 来源:网络整理
导读:我有一个MVC应用程序,我使用StyleBundle类渲染CSS文件像这样: bundles.Add(new StyleBundle("~/bundles/css").Include("~/Content/*.css")); 我有的问题是,在调试模式下,CSS网址单独渲染,我有一个Web代理积极缓存这些网址。在发布模式下,我知道一个查
我有一个MVC应用程序,我使用StyleBundle类渲染CSS文件像这样:
bundles.Add(new StyleBundle("~/bundles/css").Include("~/Content/*.css"));

我有的问题是,在调试模式下,CSS网址单独渲染,我有一个Web代理积极缓存这些网址。在发布模式下,我知道一个查询字符串被添加到最终的URL,以使每个发布的任何缓存无效。

是否有可能配置StyleBundle在调试模式下添加一个随机查询字符串,以产生以下输出来解决缓存问题?

<link href="/stylesheet.css?random=some_random_string" rel="stylesheet"/>

解决方法

您可以创建一个自定义IBundleTransform类来做到这一点。这里有一个例子,将使用文件内容的哈希附加一个v = [filehash]参数。
public class FileHashVersionBundleTransform: IBundleTransform
{
    public void Process(BundleContext context,BundleResponse response)
    {
        foreach(var file in response.Files)
        {
            using(FileStream fs = File.OpenRead(HostingEnvironment.MapPath(file.IncludedVirtualPath)))
            {
                //get hash of file contents
                byte[] fileHash = new SHA256Managed().ComputeHash(fs);

                //encode file hash as a query string param
                string version = HttpServerUtility.UrlTokenEncode(fileHash);
                file.IncludedVirtualPath = string.Concat(file.IncludedVirtualPath,"?v=",version);
            }                
        }
    }
}

然后,您可以通过将类添加到您的bundle的Transforms集合来注册该类。

new StyleBundle("...").Transforms.Add(new FileHashVersionBundleTransform());

现在只有文件内容改变时版本号才会改变。

(编辑:李大同)

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

    推荐文章
      热点阅读