c# - 使用 Application_BeginRequest + 重定向进行 HTML 版本控制中的 Javascript、CSS

标签 c# caching browser-cache durandal

这段代码可以完成 JavaScript 版本控制的工作吗?

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var request = HttpContext.Current.Request;
        var uri = request.Url;
        var url = request.Url.ToString();

        if (url.EndsWith(".js") || url.EndsWith(".css") || url.EndsWith(".html") || url.EndsWith(".ts"))
        {
            var v = Assembly.GetExecutingAssembly().GetName().Version;
            var newUrl = uri.LocalPath + "?version=" + v;

            Console.WriteLine(string.Format("changing {0} to {1}", url, newUrl));

            HttpContext.Current.Response.Redirect(newUrl);
        }
    }

尝试访问 http://localhost:1111111/App/common/Action.js 时浏览器被重定向到http://localhost:1111111/App/common/Action.js?version=1.0.0.24754 。当服务器版本改变时,clientbrowser中的javascript会失效吗?

谢谢

最佳答案

是的,他们确实会这样做,更改 URL 的任何部分都会导致浏览器关闭并获取资源,其中包括查询字符串的任何部分。您可以自己检查其中的一些内容,例如查看 Chrome 开发人员工具中的“网络”选项卡:

enter image description here

这里的304状态代码意味着该项目尚未在服务器上修改,因此浏览器可以从缓存中获取。另外,在上面的请求中,您可以看到浏览器实际上已经从缓存中加载了。

有一篇相当不错的文章here它展示了如何修改查询字符串以包含文件的最后修改日期 - 意味着自动免费版本控制。

关于c# - 使用 Application_BeginRequest + 重定向进行 HTML 版本控制中的 Javascript、CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32134286/

相关文章:

c# - "This BackgroundWorker states that it doesn' t 报告进度。”- 为什么?

node.js - 在 expressjs 中构建管理面板,无需大量查询即可计算用户数量的最佳方式?

ios - 在 iOS 中清除 safari 缓存

html - CSS 浏览器缓存

node.js - 利用浏览器缓存外部文件

c# - 创建泛型类型实例的方法

c# - 通过 C# 更改 Windows Mobile 5 主题

javascript - Jqueryvalidate 的 .validate() 方法在 ASP Core 中不执行

android - Retrofit with OKHttp 在离线时如何使用缓存数据

javascript - Ext JS 类的最佳实践最终会产生过多的 .js 文件。性能怎么样?