Search code examples
c#asp.netasp.net-mvccachingbrowser-cache

How Force browser to reload cached static file with versioning?



After deploying a new version of a website the browser loads everything from its cache from the old webpage until a hard, force refresh is done.

In ASP.NET MVC if the file becomes in Bundle, it handled by Optimization framework. a version added to your file link, and if a change occurs in your bundle's file a new token generate. follow below code :

for example, js file name is: datatables

when you put it in a bundle with the same name, you will see the

datatables?v=anY9_bo7KitrGnXQr8ITP3ylmhQe9NDzSjgLpLQWQFE1

as a file name. change datatables and watch again the name of the file in the browser, surely it will change:

datatables?v=r8yhQBxKyDgrOGyqr1ndtdG92Ije09nqTY7yogrOSTk1

But there's two questions:

  • What we can do if our file wasn't in Bundle?
  • Is a way to force the browser to refresh cache?

Solution

  • we have one solution with some different way for implementation. we use above solution for it.

    datatables?v=1
    

    we can handle the version of the file, it's mean that every time that we change our file, change the version of it too. but it's not a suitable way.

    another way used Guide, it wasn't suitable too, because each time it fetches the file and doesn't use from the browser cache.

    datatables?v=Guid.NewGuid()
    

    The last way that is the best Way is :

    when file change occur , change version too. check follow code :

    <script src="~/scripts/[email protected](Server.MapPath("/scripts/main.js")).ToString("yyyyMMddHHmmss")"></script>
    

    by this way, when you change the file, LastWriteTime change too, so the version of the file will change and in the next when you open the browser, it detects a new file and fetch it.