Controlling Caching in a generic handler (.ashx)

While working on a code update today I came across the following comment left by another developer.

“IE is stupid and caches every GET request with the same URL. In order to guarantee that no caching happens, we will make sure every GET URL is unique by adding a timestamp onto the URL as a GET parameter. We do nothing else with it.”

Well this certainly does work, but a better option is to set your caching policy in your ASHX file. IE isn’t actually being stupid here. It’s simply trying to be efficient based on it’s local caching policy. This is actually a behavior we want, and it can save round trips if the same resources are used over and over. This is a topic I’ve talked about in the past.

So, how do you control the caching policy? Well the following line of code get’s the job done in my current case.

context.Response.Cache.SetCacheability(HttpCachability.NoCache);

In the ProcessRequest method of your http handler class, context is of type “HttpContext”. If you want to allow caching, you can do that with the Cache object as well. For example you could set the cache to expire after a set time limit.

context.Response.Cache.SetCacheability(HttpCachability.Public);
context.Response.Cache.SetExpires(DateTime.Now.AddDays(1));

Here is the MSDN link for the Cache object, for further reading.

Happy coding!