我发现了很多关于让浏览器避免缓存动态内容(例如 .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,并且想要缓存静态内容,请按照 documentation 在 web.config 中添加以下内容: :
<configuration>
<system.webServer>
<staticContent>
<clientCache httpExpires="Sun, 27 Sep 2015 00:00:00 GMT" cacheControlMode="UseExpires" />
</staticContent>
</system.webServer>
</configuration>
关于c# - 使用 ASP.Net,如何为静态内容启用浏览器缓存并为动态内容禁用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7526381/