c# – 使用ASP.Net,如何为静态内容启用浏览器缓存并为动态内容禁用它?
作者:互联网
关于让浏览器避免缓存动态内容(例如.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();
}
}
}
解决方法:
如果您使用的是IIS7&并且您想要缓存静态内容在web.config中添加以下内容:
<staticContent>
<clientCache httpExpires="Sun, 27 Sep 2015 00:00:00 GMT" cacheControlMode="UseExpires" />
</staticContent>
标签:c,asp-net,asp-net-4-0 来源: https://codeday.me/bug/20190716/1482162.html