防止以编程方式缓存脚本

我想问一下是否有办法阻止Firefox缓存脚本(.js文件)。

我有一个项目(ASP.Net Web App)在firefox上有缓存问题。 当我第一次运行应用程序(脚本在firefox上缓存)并修改脚本并重新运行应用程序时,firefox正在使用缓存的脚本而不是更新的脚本。

我正在使用Firefox 3.6.13。

我已经尝试过使用HttpHeaders但似乎firefox忽略了我的代码。

这是我的代码:

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false); HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); HttpContext.Current.Response.Cache.SetNoStore(); 

我尝试将此代码放在global.asax> Application_BeginRequest和MasterPage.aspx.cs> Page_Load中,但它无效。

提前致谢。

你应该可以使用

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

但是你必须有一个http处理程序,它将脚本直接呈现给响应流,而不是将脚本标记的源url设置为处理程序,或者将IIS配置为使用特定处理程序处理所有javascripts:将* .js指向aspnet_isapi .dll ISAPI扩展,然后在web.config中添加以下内容

      

而不是处理程序:

 namespace skmHttpHandlers { public class JavascriptHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.Clear(); context.Response.Cache.SetCacheability(HttpCacheability.NoCache) using (var scriptStream = File.Open(Server.MapPath("~/script/TheScript.js"), FileMode.Open)) scriptStream.CopyTo(context.Response.OutputStream); context.Response.End(); } public bool IsReusable { get { return false; } } } } 

一种技术是将随机元素作为查询字符串添加到URL,因此浏览器不知道如何缓存脚本:

  

更好的方法是附加程序集的当前内部版本号,以便在脚本未更改时获得脚本缓存的性能优势。 但是,如果您从未使用二进制版本“带外”更改脚本文件,则此方法仍然有效。

1)安装IIS模块: http : //www.iis.net/download/urlrewrite

2)将此文件放入web.config中:

              

3)编写这个辅助函数(进入某个全局类)

 public static string PutCSS(string filepath) { FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(filepath)); string timestamp = f.LastWriteTimeUtc.Year.ToString() + f.LastWriteTimeUtc.Month.ToString() + f.LastWriteTimeUtc.Day.ToString() + f.LastWriteTimeUtc.Hour.ToString() + f.LastWriteTimeUtc.Minute.ToString() + f.LastWriteTimeUtc.Second.ToString() + f.LastWriteTimeUtc.Millisecond.ToString(); return "\n"; } public static string PutJS(string filepath) { FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(filepath)); string timestamp = f.LastWriteTimeUtc.Year.ToString() + f.LastWriteTimeUtc.Month.ToString() + f.LastWriteTimeUtc.Day.ToString() + f.LastWriteTimeUtc.Hour.ToString() + f.LastWriteTimeUtc.Minute.ToString() + f.LastWriteTimeUtc.Second.ToString() + f.LastWriteTimeUtc.Millisecond.ToString(); return "\n"; } 

4)而不是:

   

使用:

 <%= global.PutCSS("Styles/style.css")%> <%= global.PutCSS("Javascript/userscript.css")%> 

如果您可以控制IIS配置,则可以将所有脚本放在一个文件夹中,并告诉IIS立即使内容过期,或者添加您选择的其他自定义标头。

IIS 6.0的相应页面是http://technet.microsoft.com/en-us/library/cc732442.aspx

  <%= "" %>  

我想要缓存脚本和样式…只有在它们改变时重新加载…使用文件的日期很容易: