How to use output caching on .ashx handler

Kieran Benton picture Kieran Benton · Jul 10, 2009 · Viewed 29.2k times · Source

How can I use output caching with a .ashx handler? In this case I'm doing some heavy image processing and would like the handler to be cached for a minute or so.

Also, does anyone have any recommendations on how to prevent dogpiling?

Answer

BigBlondeViking picture BigBlondeViking · Jul 10, 2009

There are some good sources but you want to cache you processing server side and client-side.

Adding HTTP headers should help in the client side caching

here are some Response headers to get started on..

You can spend hours tweaking them until you get the desired performance

//Adds document content type
context.Response.ContentType = currentDocument.MimeType;
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
context.Response.Cache.SetMaxAge(new TimeSpan(0,10,0)); 
context.Response.AddHeader("Last-Modified", currentDocument.LastUpdated.ToLongDateString());

// Send back the file content
context.Response.BinaryWrite(currentDocument.Document);

As for server side caching that is a different monster... and there are plenty of caching resources out there...