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

2

5

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();
        }
    }
}
Eulaheulalee answered 23/9, 2011 at 8:43 Comment(0)
O
10

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>
Oxysalt answered 23/9, 2011 at 8:51 Comment(5)
Fantastic! So much more simple too. Could the issues I was having before (controlling caching from Application_BeginRequest) have anything to do with using Visual Studio Development Server? Also, is there a similar tag for dynamic content?Eulaheulalee
I don't think Visual Studio Development Server had anything to do with it. Are you going to use Page caching? If yes, you can control the duration with a web.config setting.Oxysalt
I would like to ensure that dynamic content is not cached at all. The code in Application_BeginRequest does this well. I have added .axd to the _fileExtensionsToCache, which seems to prevent their browser cache settings from being overridden here. Just asking in case there was a better way to do this, i.e. in the web.config.Eulaheulalee
:) :) your cache expires today.. What are the chances:)Miguelmiguela
@Miguelmiguela - ha ha! I can't even remember writing the answer - that exact date is probably on a live server somewhere stuck in the past, oops. :)Oxysalt
S
3

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

Southernmost answered 23/9, 2011 at 8:52 Comment(2)
Shouldn't the line "cache.SetExpires(DateTime.UtcNow.AddDays(1))" add expiry date to the response header?Eulaheulalee
Yes, it should, maybe the problem is in SetCacheAbility method, see codeclimber.net.nz/archive/2007/04/01/…Whiffletree

© 2022 - 2024 — McMap. All rights reserved.