我有一个MVC应用程序,我使用StyleBundle类来渲染CSS文件,如下所示:
bundles.Add(new StyleBundle("~/bundles/css").Include("~/Content/*.css"));我遇到的问题是,在Debug模式下,CSS是单独呈现的,而我有一个web代理来积极地缓存这些urls。在Release模式下,我知道会将一个查询字符串添加到最终的url中,以使每个版本的缓存无效。
是否可以将StyleBundle配置为在Debug模式下添加一个随机查询字符串,以生成以下输出来绕过缓存问题?
<link href="/stylesheet.css?random=some_random_string" rel="stylesheet"/>发布于 2014-10-21 23:32:24
您可以创建自定义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);
}
}
}
}然后,您可以通过将该类添加到捆绑包的Transforms集合来注册该类。
new StyleBundle("...").Transforms.Add(new FileHashVersionBundleTransform());现在,只有当文件内容发生变化时,版本号才会发生变化。
发布于 2016-05-10 00:02:45
您只需要一个唯一的字符串。它不一定是Hash。我们使用文件的LastModified日期并从中获取刻度。正如@Todd指出的那样,打开和读取文件的成本很高。Ticks足以输出一个唯一的数字,该数字会在文件更改时发生变化。
internal static class BundleExtensions
{
public static Bundle WithLastModifiedToken(this Bundle sb)
{
sb.Transforms.Add(new LastModifiedBundleTransform());
return sb;
}
public class LastModifiedBundleTransform : IBundleTransform
{
public void Process(BundleContext context, BundleResponse response)
{
foreach (var file in response.Files)
{
var lastWrite = File.GetLastWriteTime(HostingEnvironment.MapPath(file.IncludedVirtualPath)).Ticks.ToString();
file.IncludedVirtualPath = string.Concat(file.IncludedVirtualPath, "?v=", lastWrite);
}
}
}
}以及如何使用它:
bundles.Add(new StyleBundle("~/bundles/css")
.Include("~/Content/*.css")
.WithLastModifiedToken());MVC是这样写的:
<link href="bundles/css/site.css?v=635983900813469054" rel="stylesheet"/>脚本包也能很好地工作。
发布于 2015-01-11 20:19:10
您可以将HashCache应用于BundlesCollection中的所有bundle
在将所有包添加到集合之后,对BundlesCollection实例执行ApplyHashCache()扩展方法。
BundleTable.Bundles.ApplyHashCache();或者,您可以将HashCache应用于单个捆绑包
创建HashCacheTransform的实例,并将其添加到要应用HashCache的捆绑包实例中。
var myBundle = new ScriptBundle("~/bundle_virtual_path").Include("~/scripts/jsfile.js");
myBundle.Transforms.Add(new HashCacheTransform());https://stackoverflow.com/questions/15005481
复制相似问题