Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting optimum http caching headers and server params in ASP.Net MVC and IIS 7.5

I have an ASP.Net site (happens to be MVC, but that's not relevant here) with a few pages I'd like cached really well.

Specifically I'd like to achieve:

  1. output cached on the server for 2 hours.
  2. if the file content on the server changes, that output cache should be flushed for that page
  3. cached in the browser for 10 minutes (i.e. don't even ask the server if it's that fresh)
  4. when the browser does make an actual subsequent request, I'd like it to use etags, so that the server can return a 304 if not modified.

(note - time values above are indicative examples only)

  • 1) and 2) I can achieve by Response.Cache.SetCacheability(HttpCacheability.Server)
  • I know 3) can be achieved by using max-age and cache-control:private
  • I can emit etags with Response.Cache.SetETagFromFileDependencies();

but I can't seem to get all of these things to work together. Here's what I have:

    Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
        Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        Response.Cache.SetETagFromFileDependencies();
        Response.Cache.SetValidUntilExpires(true);
        Response.Cache.SetMaxAge(TimeSpan.FromSeconds(60 * 10));

Is the scenario I want possible? In particular:

  • can browsers do both 3) and 4) like that? When Firefox issues a new request after it expires in the local cache, it does indeed send the etag the server responded with before, but I get a 200 response.
  • setting the variables like above, where would I set the duration of the output caching?

Thanks for any tips!

like image 319
Nik Avatar asked Sep 13 '10 21:09

Nik


1 Answers

I'm not sure if you've solved this problem yet (several months later...), but this should be possible.

SetMaxAge should set the amount of "guarranteed" fresh time. If you additionally send an ETag, you'll have satisfied 3 & 4. Requirements 1 & 2 can be solved orthogonally with whatever server-side caching mechanism you use: I've never used ASP.NET server-side cache like this, but it's almost certainly possible.

I'd remove extraneous headers from your responses such as SetRevalidation - why would this be necessary?

like image 74
Eamon Nerbonne Avatar answered Sep 19 '22 09:09

Eamon Nerbonne