asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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());

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

大佬总结

以上是大佬教程为你收集整理的caching – MVC4 StyleBundle:你能在Debug模式下添加一个缓存清除查询字符串吗?全部内容,希望文章能够帮你解决caching – MVC4 StyleBundle:你能在Debug模式下添加一个缓存清除查询字符串吗?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。