Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With ASP.Net, how do I enable browser caching for static content and disable it for dynamic content?

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();
        }
    }
}
like image 512
Evil Pigeon Avatar asked Dec 12 '22 09:12

Evil Pigeon


2 Answers

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>
like image 132
Joe Ratzer Avatar answered Dec 14 '22 23:12

Joe Ratzer


The magic is made by HTTP headers - see this page.

like image 22
Karel Frajták Avatar answered Dec 14 '22 23:12

Karel Frajták