MVC4 StyleBundle:可以在“调试"模式下添加缓存清除查询字符串吗? [英] MVC4 StyleBundle: Can you add a cache-busting query string in Debug mode?

查看:74
本文介绍了MVC4 StyleBundle:可以在“调试"模式下添加缓存清除查询字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MVC应用程序,并且正在使用StyleBundle类来渲染CSS文件,如下所示:

I've got an MVC application and I'm using the StyleBundle class for rendering out CSS files like this:

bundles.Add(new StyleBundle("~/bundles/css").Include("~/Content/*.css"));

我遇到的问题是,在Debug模式下,CSS URL分别呈现出来,并且我有一个Web代理来积极地缓存这些URL.在Release模式下,我知道将查询字符串添加到最终URL中,以使每个版本的所有缓存均无效.

The problem I have is that in Debug mode, the CSS urls are rendered out individually, and I have a web proxy that aggressively caches these urls. In Release mode, I know a query string is added to the final url to invalidate any caches for each release.

是否可以配置StyleBundleDebug模式下添加随机查询字符串,并产生以下输出来解决缓存问题?

Is it possible to configure StyleBundle to add a random querystring in Debug mode as well to produce the following output to get around the caching issue?

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

推荐答案

您可以创建一个自定义IBundleTransform类来执行此操作.这是一个示例,该示例将使用文件内容的哈希值附加v = [filehash]参数.

You can create a custom IBundleTransform class to do this. Here's an example that will append a v=[filehash] parameter using a hash of the file contents.

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

然后您可以通过将其添加到包的Transforms集合中来注册该类.

You can then register the class by adding it to the Transforms collection of your bundles.

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

现在,版本号仅在文件内容更改时更改.

Now the version number will only change if the file contents change.

这篇关于MVC4 StyleBundle:可以在“调试"模式下添加缓存清除查询字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆