我发现很多有关获取浏览器以避免缓存动态内容(例如.aspx页面)的好信息,但是我没有成功获取浏览器来缓存我的静态内容,特别是css,javascript和图像文件。使用ASP.Net,如何为静态内容启用浏览器缓存并禁用动态内容?
我一直在使用Application.BeginRequest Global.asax没有成功。为静态内容分配服务器不是我们的选择。我也想避免必须配置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();
}
}
}
太棒了!太简单了。我以前遇到的问题(从Application_BeginRequest控制缓存)与使用Visual Studio Development Server有什么关系?另外,是否有类似的动态内容标签? –
我不认为Visual Studio Development Server与它有任何关系。你打算使用页面缓存吗?如果是,您可以使用web.config设置来控制持续时间。 –
我想确保动态内容不会被缓存。 Application_BeginRequest中的代码做得很好。我已将.axd添加到_fileExtensionsToCache,这似乎阻止了浏览器缓存设置在此处被覆盖。只是询问是否有更好的方法来做到这一点,即在web.config中。 –