MVC4 StyleBundle: Can you add a cache-busting query string in Debug mode?

后端 未结 6 1534
不思量自难忘°
不思量自难忘° 2020-12-13 06:16

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         


        
6条回答
  •  无人及你
    2020-12-13 06:45

    Note this is written for Scripts but also works for Styles (just change those key words)

    Building on @Johan's answer:

    public static IHtmlString RenderBundle(this HtmlHelper htmlHelper, string path)
    {
        var context = new BundleContext(htmlHelper.ViewContext.HttpContext, BundleTable.Bundles, string.Empty);
        var bundle = System.Web.Optimization.BundleTable.Bundles.GetBundleFor(path);
        var html = System.Web.Optimization.Scripts.Render(path).ToString();
        foreach (var item in bundle.EnumerateFiles(context))
        {
            if (!html.Contains(item.Name))
                continue;
    
            html = html.Replace(item.Name, item.Name + "?" + item.LastWriteTimeUtc.ToString("yyyyMMddHHmmss"));
        }
    
        return new HtmlString(html);
    }
    
    public static IHtmlString RenderStylesBundle(this HtmlHelper htmlHelper, string path)
    {
        var context = new BundleContext(htmlHelper.ViewContext.HttpContext, BundleTable.Bundles, string.Empty);
        var bundle = System.Web.Optimization.BundleTable.Bundles.GetBundleFor(path);
        var html = System.Web.Optimization.Styles.Render(path).ToString();
        foreach (var item in bundle.EnumerateFiles(context))
        {
            if (!html.Contains(item.Name))
                continue;
    
            html = html.Replace(item.Name, item.Name + "?" + item.LastWriteTimeUtc.ToString("yyyyMMddHHmmss"));
        }
    
        return new HtmlString(html);
    }
    

    Usage:

    @Html.RenderBundle("...")
    @Html.RenderStylesBundle("...")
    

    Replacing

    @Scripts.Render("...")
    @Styles.Render("...")
    

    Benefits:

    • Works for v1.0.0.0 of System.Web.Optimizations
    • Works on multiple files in the bundle
    • Gets the file modification date, rather than hashing, of each file, rather than a group

    Also, when you need to quickly workaround Bundler:

    public static MvcHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var resolvedUrl = urlHelper.Content(url);
    
        if (resolvedUrl.ToLower().EndsWith(".js") || resolvedUrl.ToLower().EndsWith(".css"))
        {
            var localPath = HostingEnvironment.MapPath(resolvedUrl);
            var fileInfo = new FileInfo(localPath);
            resolvedUrl += "?" + fileInfo.LastWriteTimeUtc.ToString("yyyyMMddHHmmss");
        }
    
        return MvcHtmlString.Create(resolvedUrl);
    }
    

    Usage:

    
    

    Replacing:

    
    

    (Also replaces many other alternative lookups)

提交回复
热议问题