关于让浏览器避免缓存动态内容(例如.aspx页面),我发现了很多很好的信息,但是我没有成功地让浏览器缓存我的静态内容,特别是css,javascript和图像文件。
我一直在使用Global.asax中的Application_BeginRequest而没有成功。拥有一个单独的静态内容服务器不是我们的选择。我还想避免配置IIS设置,除非可以从web.config控制它们。禁用aspx页面的缓存是否会影响其上显示的静态内容的缓存?
如果以前已经回答过这个问题,我很抱歉。作为讨论的起点,这是我的Global.asax文件背后的代码。
public class Global_asax : System.Web.HttpApplication
{
private static HashSet<string> _fileExtensionsToCache;
private static HashSet<string> FileExtensionsToCache
{
get
{
if (_fileExtensionsToCache == null)
{
_fileExtensionsToCache = new HashSet<string>();
_fileExtensionsToCache.Add(".css");
_fileExtensionsToCache.Add(".js");
_fileExtensionsToCache.Add(".gif");
_fileExtensionsToCache.Add(".jpg");
_fileExtensionsToCache.Add(".png");
}
return _fileExtensionsToCache;
}
}
public void Application_BeginRequest(object sender, EventArgs e)
{
var cache = HttpContext.Current.Response.Cache;
if (FileExtensionsToCache.Contains(Request.CurrentExecutionFilePathExtension))
{
cache.SetExpires(DateTime.UtcNow.AddDays(1));
cache.SetValidUntilExpires(true);
cache.SetCacheability(HttpCacheability.Private);
}
else
{
cache.SetExpires(DateTime.UtcNow.AddDays(-1));
cache.SetValidUntilExpires(false);
cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetNoStore();
}
}
}
答案 0 :(得分:9)
如果您使用的是IIS7&amp;并且您想要缓存静态内容,请在web.config中添加以下内容:
<staticContent>
<clientCache httpExpires="Sun, 27 Sep 2015 00:00:00 GMT" cacheControlMode="UseExpires" />
</staticContent>
答案 1 :(得分:2)
魔术是由HTTP标头制作的 - 请参阅此page。