Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

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

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

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.

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"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You just need a unique string. It doesn't have to be Hash. We use the LastModified date of the file and get the Ticks from there. Opening and reading the file is expensive as @Todd noted. Ticks is enough to output a unique number that changes when the file is changed.

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

and how to use it:

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

and this is what MVC writes:

<link href="bundles/css/site.css?v=635983900813469054" rel="stylesheet"/>

works fine with Script bundles too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...