caching – MVC4 StyleBundle:你能在Debug模式下添加一个缓存清除查询字符串吗?

我有一个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());

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

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...