小编典典

强制浏览器在asp.net应用程序中获取最新的js和css文件

c#

某些浏览器会缓存js和css文件,除非您强制将它们刷新,否则它们将无法刷新。最简单的方法是什么。

我刚刚实施了似乎可行的解决方案。

在页面上声明一个版本变量

  public string version { get; set; }

从web.config密钥获取版本号

 version = ConfigurationManager.AppSettings["versionNumber"];

在您的aspx页面中,像这样调用javascript和样式表

<script src="scripts/myjavascript.js?v=<%=version %>" type="text/javascript"></script>
<link href="styles/mystyle.css?v=<%=version %>" rel="stylesheet" type="text/css" />

因此,如果您在web.config中将1.0的版本设置为1.1,则浏览器将下载最新文件,这有望为您和您的用户省去一些麻烦。

是否有另一种更好的解决方案,还是会对网站造成无法预料的问题?


阅读 497

收藏
2020-05-19

共1个答案

小编典典

我通过添加最后修改的时间戳作为脚本的查询参数来解决此问题。

我使用扩展方法进行了此操作,并在CSHTML文件中使用了它。 注意: 此实现将时间戳缓存1分钟,因此我们不会对磁盘​​造成太大的影响。

这是扩展方法:

public static class JavascriptExtension {
    public static MvcHtmlString IncludeVersionedJs(this HtmlHelper helper, string filename) {
        string version = GetVersion(helper, filename);
        return MvcHtmlString.Create("<script type='text/javascript' src='" + filename + version + "'></script>");
    }

    private static string GetVersion(this HtmlHelper helper, string filename)
    {
        var context = helper.ViewContext.RequestContext.HttpContext;

        if (context.Cache[filename] == null)
        {
            var physicalPath = context.Server.MapPath(filename);
            var version = $"?v={new System.IO.FileInfo(physicalPath).LastWriteTime.ToString("MMddHHmmss")}";
            context.Cache.Add(filename, version, null,
              DateTime.Now.AddMinutes(5), TimeSpan.Zero,
              CacheItemPriority.Normal, null);
            return version;
        }
        else
        {
            return context.Cache[filename] as string;
        }
    }
}

然后在CSHTML页面中:

 @Html.IncludeVersionedJs("/MyJavascriptFile.js")

在呈现的HTML中,其显示为:

 <script type='text/javascript' src='/MyJavascriptFile.js?20111129120000'></script>
2020-05-19