Sponsored

Thursday, November 7, 2013

Setting Cache Control HTTP Headers in Web API Controller Method

Controlling caching behaviour of an HTTP response is an important task that cannot be ignored as it will have a big impact on a web application load and performance. In ASP.NET Web Forms and MVC applications it usually is done by using special directives or attributes that take care of adding corresponding headers to the response. ASP.NET Web API framework unfortunately does not come with an out of the box support for this functionality so concious developers need to deal with that themselves. Luckily it is not a difficult task to do as the Web API framework has a number of support objects that simplify the job.

Basically in order to control caching behaviour we need to make sure that the output response will have what is called "Cache control header" with proper values that determine caching behaviour. Example below demonstrates how to make a response publicly cacheable for a period of time:
   var response = new HttpResponseMessage();
   response.Headers.CacheControl = new CacheControlHeaderValue
          {Public = true, MaxAge = TimeSpan.FromSeconds(maxAge)};

To simplify the usage further we can even create a static extension method that can be easily applied in a controller method:
// somewhere in a static class
public static HttpResponseMessage PublicCache(this HttpResponseMessage response, int maxAge)
{
   response.Headers.CacheControl = new CacheControlHeaderValue
          {Public = true, MaxAge = TimeSpan.FromSeconds(maxAge)};
   return response;
}
...
// inside an ApiController class
public HttpResponseMessage MyApiMethod(long id)
{
   var response = new HttpResponseMessage();
   ..............
   return response.PublicCache(24 * 7 * 60);
}

No comments:

Post a Comment