2

As a developer we all had this problem: you need to do maintenance on a website and there is clientscript: foo.js Now you make changes to foo.js and you test it, check in, deploy the new code on the test environment. Now the test user claims you did not fix the problem, because his browser still holds the old foo.js in cache.

I was thinking of creating a hash of the filecontents and use that in the filename. foo_8c736521.js I could create the hash -> rename the file -> and update the BundleConfig.cs But I want this to be done automatically within visual studio.

Is there a library of some sort that handles this for me in C# .NET?

I have added this transformation to my web.Test.config file:

  <system.web>
        <compilation debug="false" targetFramework="4.5"  xdt:Transform="Replace" />
  </system.web>

Now the Bundle optimizations are enabled in this environment. And it works.

  • 1
    foo.js?v= – aabilio Jan 11 '17 at 12:41
  • @aabilio That would force the browser to always get the file, effectively disabling the caching mechanism. I only want to disable the cache, when the actual file contents have changed. – Tony_KiloPapaMikeGolf Jan 11 '17 at 12:42
  • oh I see, I did not understand the question. So, if you control the server I would use Etag and/or Last-Modified HTTP Headers... – aabilio Jan 11 '17 at 12:47
  • You must create a unique URL per file version (using a query string, or changing the filename). If you are using ASP.NET you should search for "bundle" on Google. If you are using ASP.NET Core, you should check [this blog post](http://www.softfluent.com/blog/dev/2017/01/08/Caching-static-resources-forever-with-ASP-NET-Core) – meziantou Jan 11 '17 at 12:47
  • Possible duplicate: [How can I force clients to refresh JavaScript files?](http://stackoverflow.com/q/32414/1260204) – Igor Jan 11 '17 at 12:57

1 Answers1

3

If you are using ASP.NET version 4.5 or above, use the built-in JS Bundler. It will keep track of changes to the JS files contained in the bundle and issue a new hash only when a file has changed.

public class BundleConfig {
    public static void RegisterBundles(BundleCollection bundles) {
         bundles.Add(new ScriptBundle("~/bundles/custom").Include(
             "~/Scripts/foo.js",
             "~/Scripts/bar.js"
         ));
    }
}

For MVC - register bundles in Global.asax:

protected void Application_Start() {
    // ...
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

See ASP.NET - Bundling and Minification

Georg Patscheider
  • 8,808
  • 1
  • 21
  • 34
  • This was already implemented in the project. I only had to set the debug="false" option in the test environment web.config to enable the bundle optimization. – Tony_KiloPapaMikeGolf Jan 11 '17 at 14:17
  • `debug="true"` can be used in development environments to disable bundling and minification to make it easier to debug the scripts. – Georg Patscheider Jan 11 '17 at 14:31