简体   繁体   English

如何在Visual Studio中自动将md5哈希的版本号添加到javascript和CSS文件中,或使用另一种方式强制浏览器缓存刷新?

[英]How to automatically add version numbers of md5 hash to javascript and css files in Visual Studio or use another way to force browser cache refresh?

Whenever I put out a new version of CSS or javascript files for any of our web applications, I manually add a ?v=# to the URL in the head of the HTML (# is a version number, like 3 or 10) to make sure the users browser cache isn't standing in the way of the changes. 每当我为任何Web应用程序发布新版本的CSS或javascript文件时,我都会在HTML开头的URL中手动添加?v=# (#是版本号,例如3或10),确保用户浏览器缓存不会妨碍更改。

But some applications have multiple CSS and multiple JS files in the head and it is tedious to keep track of all changed files. 但是某些应用程序的头部具有多个CSS和多个JS文件,并且要跟踪所有已更改的文件很繁琐。

We use the ASP.NET platform on an IIS server, so using the answer to What is an elegant way to force browsers to reload cached CSS/JS files? 我们在IIS服务器上使用ASP.NET平台,因此使用答案是强制浏览器重新加载缓存的CSS / JS文件的一种优雅方法是什么? is not possible but I am looking for something similar. 是不可能的,但我正在寻找类似的东西。 Preferably all javascript. 最好所有的JavaScript。

I like the suggestion in that post to use a md5 hash but I cannot seem to find a way to calculate the checksum of a CSS or JS file. 我喜欢该帖子中使用md5哈希的建议,但似乎无法找到一种计算CSS或JS文件的校验和的方法。

The code would look something like this (using jQuery): 代码看起来像这样(使用jQuery):

$.each($("script[type='text\javascript']"),function(){
    $(this).attr("src",$(this).attr("src") + "?v=" + checkMD5Sum($(this).attr("src")) );
});

function checkMD5Sum(url){
    //get the hash or something to auto version the file
    //I could send the url or filename to a webmethod to get the MD5 check sum, but doing this after page load is not usefull, so what to do?
}

Or perhaps using a postbuild process in Visual Studio, but I have never done that, so I am reluctant to try. 或者也许在Visual Studio中使用了postbuild流程,但是我从未做过,所以我不愿意尝试。


Edit 编辑

Going to try this in the web.config as per Adding Caching Profiles 按照添加缓存配置文件在web.config中尝试此操作

<configuration>
   <system.webServer>
      <caching enabled="true">
         <profiles>
            <add extension=".js" policy="CacheUntilChange" />
            <add extension=".css" policy="CacheUntilChange" />
         </profiles>
      </caching>
   </system.webServer>
</configuration>

Your solution seems to require the browser to fetch the file twice, and you're given no guarantee of the state of the first fetch. 您的解决方案似乎要求浏览器两次提取文件,并且不能保证第一次提取的状态。 So it doesn't work. 因此它不起作用。

Caching is directed by the server. 缓存由服务器控制。 It's not possible to decide when a new version is available on the client - unless you ignore the cache and always fetch a fresh copy. 无法决定何时在客户端上提供新版本-除非您忽略缓存并始终获取新副本。

There are many ways to implement a caching policy. 有很多方法可以实现缓存策略。 Fingerprinting with a version number is one of them. 具有版本号的指纹就是其中之一。

I prefer to use ETag s. 我更喜欢使用ETag Have the ETag be the filemtime and you're good. 让ETag成为filemtime,您就很好了。

  VersionNumber = System.Configuration.ConfigurationManager.AppSettings["Version"];

    //Caching Issues For JS
    public static string JSVersionUpdate(string JsFile)
    {
        StringBuilder str = new StringBuilder();
        str.Append(GetQualifiedPath(JsFile));
        str.Append("?Version=");
        str.Append(VersionNumber);
        return str.ToString();
    }

    public static void DiscardVersion()
    {
        VersionNumber = null;
    }

    //get Full Path for JS File
    private static string GetQualifiedPath(string path)
    {
        var httpRequestBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);

        path = path.Replace("~", string.Empty);

        string appPath = string.Empty;
        if (httpRequestBase != null)
        {
            //Formatting the fully qualified website url/name
            appPath = string.Format("{0}://{1}{2}{3}{4}",
                        httpRequestBase.Request.Url.Scheme,
                        httpRequestBase.Request.Url.Host,
                        httpRequestBase.Request.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Request.Url.Port,
                        httpRequestBase.Request.ApplicationPath,
                        path);
        }
        appPath = appPath.TrimEnd('/');

        return appPath;
    } 
}

In UI Page : script src="JSVersionUpdate("~/Scripts/Application/Abc.js")" 在用户界面页面中: script src="JSVersionUpdate("~/Scripts/Application/Abc.js")"

O/p : ~/Scripts/Application/Abc.js/version=1.0 O / p: ~/Scripts/Application/Abc.js/version=1.0

Browser request for JS Files from server only if Version is Different else it will cached out.Now i don't need to tell someone to clear the cache again and again after deployment.Only thing i do is i change Version Number in Web Config 浏览器仅在版本不同的情况下才从服务器请求JS文件,否则它将被缓存出去。现在我不需要告诉别人在部署后一次又一次清除缓存。我要做的只是在Web Config中更改版本号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM