I have found a lot of good information with regards to getting browsers to avoid caching dynamic content (e.g. .aspx pages), however I have not been successful with getting browsers to cache my static content, specifically css, javascript and image files.
I have been playing with Application_BeginRequest in Global.asax without success. Having a separate server for static content is not an option for us. I would also like to avoid having to configure IIS settings unless they can be controlled from the web.config. Could disabling caching for an aspx page influence the caching of static content that appears on it?
I apologise if this question has been answered previously.
As a starting point for discussion, here is the code behind for my Global.asax file.
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();
}
}
}
If you are using IIS7 & and you want to cache static content add the following in the web.config as according to the documentation:
<configuration>
<system.webServer>
<staticContent>
<clientCache httpExpires="Sun, 27 Sep 2015 00:00:00 GMT" cacheControlMode="UseExpires" />
</staticContent>
</system.webServer>
</configuration>
The magic is made by HTTP headers - see this page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With