Implement Output Caching in Web API

At the very first, “Happy New Year ” to all. In this article we will learn to implement Output Caching in Web API applications.

This article assumes familiarity with basic caching concepts and a good understanding of the Web API of MVC based applications. If you are very new to both concepts then my recommendation is to first learn those concepts then proceed with this article.

Most probably you have implemented caching in ASP.NET and the MVC Architecture. They are pretty easy. In the case of MVC just plug in the “[OutputCache]” attribute over action and it is done. And in the case of a form-based application we have implemented Output Caching by setting a proper page directive.

But when the scenario is Web API , the situation is a little more complex. Unfortunately the Web API doesn’t have built-in support to implement caching. But we can implement the caching functionality by implementing our own class.

First of all install the following package in your Web API application.

If you are running .NET 4.5 then go for this package.

  • Install-Package Strathweb.CacheOutput.WebApi2

For .NET 4.5 , install the following one:

  • Install-Package Strathweb.CacheOutput

Now we need to implement our own caching class that will be derived from the ActionFilterAttribute class. If you have worked with various filter actions then most probably you are already familiar with this class. So, let’s proceed step-by-step.

Step 1: Derive a class from the ActionFilterAttribute class

  1. public class WebApiOutputCacheAttribute : ActionFilterAttribute  
  2. {  
  3. }

Step 2: Set the properties for the class:

  1. private int _timespan;  
  2. // client cache length in seconds  
  3. private int _clientTimeSpan;  
  4. // cache for anonymous users only?  
  5. private bool _anonymousOnly;  
  6. // cache key  
  7. private string _cachekey;  
  8. // cache repository  
  9. private static readonly ObjectCache WebApiCache = MemoryCache.Default;  

Step 3: Set the following constructor in the class:

  1. public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly)  
  2. {  
  3.     _timespan = timespan;  
  4.     _clientTimeSpan = clientTimeSpan;  
  5.     _anonymousOnly = anonymousOnly;  
  6. }

Step 4: Check whether or not the request should be cached

In this step we will implement one private function that will determine whether or not the request should be cached.

  1. private bool _isCacheable(HttpActionContext ac)  
  2. {  
  3.     if (_timespan > 0 && _clientTimeSpan > 0)  
  4.     {  
  5.         if (_anonymousOnly)  
  6.             if (Thread.CurrentPrincipal.Identity.IsAuthenticated)  
  7.                 return false;  
  8.         if (ac.Request.Method == HttpMethod.Get) return true;  
  9.     }  
  10.     Else  
  11.     {  
  12.         throw new InvalidOperationException("Wrong Arguments");  
  13.     }  
  14.     return false;  
  15. }  

Step 5: Function to enable client-side caching.

This is the function that will enable client-side caching:

  1. private CacheControlHeaderValue setClientCache()  
  2. {  
  3.     var cachecontrol = new CacheControlHeaderValue();  
  4.     cachecontrol.MaxAge = TimeSpan.FromSeconds(_clientTimeSpan);  
  5.     cachecontrol.MustRevalidate = true;  
  6.     return cachecontrol;  
  7. }
Step 6: Override the onActionExecuting() function from the ActionAttributeFilter class.

  1. public override void OnActionExecuting(HttpActionContext ac)  
  2. {  
  3.     if (ac != null)  
  4.     {  
  5.         if (_isCacheable(ac))  
  6.         {  
  7.             _cachekey = string.Join(":"new string[] { ac.Request.RequestUri.AbsolutePath, ac.Request.Headers.Accept.FirstOrDefault().ToString() });  
  8.             if (WebApiCache.Contains(_cachekey))  
  9.             {  
  10.                 var val = (string)WebApiCache.Get(_cachekey);  
  11.                 if (val != null)  
  12.                 {  
  13.                     ac.Response = ac.Request.CreateResponse();  
  14.                     ac.Response.Content = new StringContent(val);  
  15.                     var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":responsect");  
  16.                     if (contenttype == null)  
  17.                         contenttype = new MediaTypeHeaderValue(_cachekey.Split(':')[1]);  
  18.                     ac.Response.Content.Headers.ContentType = contenttype;  
  19.                     ac.Response.Headers.CacheControl = setClientCache();  
  20.                     return;  
  21.                 }  
  22.             }  
  23.         }  
  24.     }  
  25.     Else  
  26.     {  
  27.         throw new ArgumentNullException("actionContext");  
  28.     }  
  29. }

Step 7: Override the OnActionExecuted function from the ActionAttributeFilter class.

  1. public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)  
  2. {  
  3.     if (!(WebApiCache.Contains(_cachekey)))  
  4.     {  
  5.         var body = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;  
  6.         WebApiCache.Add(_cachekey, body, DateTime.Now.AddSeconds(_timespan));  
  7.         WebApiCache.Add(_cachekey + ":response-ct",  
  8. ecutedContext.Response.Content.Headers.ContentType, DateTime.Now.AddSeconds(_timespan));  
  9.     }  
  10.     if (_isCacheable(actionExecutedContext.ActionContext))  
  11.         actionExecutedContext.ActionContext.Response.Headers.CacheControl = setClientCache();  
  12. } 
Step 8: The entire code of the WebApiOutputCacheAttribute class is given below for a better understanding.
  1. public class WebApiOutputCacheAttribute : ActionFilterAttribute
  2. {
  3.     private int _timespan;
  4.     // client cache length in seconds
  5.     private int _clientTimeSpan;   
  6.     // cache for anonymous users only?
  7.     private bool _anonymousOnly;  
  8.     // cache key
  9.     private string _cachekey;
  10.     // cache repository 
  11.     private static readonly ObjectCache WebApiCache = MemoryCache.Default;
  12.     public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly)
  13.     {
  14.         _timespan = timespan;
  15.         _clientTimeSpan = clientTimeSpan;
  16.         _anonymousOnly = anonymousOnly;
  17.     }
  18.     private bool _isCacheable(HttpActionContext ac)
  19.     {
  20.         if (_timespan > 0 && _clientTimeSpan > 0)
  21.         {
  22.             if (_anonymousOnly)
  23.                 if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
  24.                     return false;
  25.             if (ac.Request.Method == HttpMethod.Get) return true;
  26.         }
  27.         else
  28.         {
  29.             throw new InvalidOperationException("Wrong Arguments");
  30.         }
  31.         return false;
  32.     }
  33.     private CacheControlHeaderValue setClientCache()
  34.     {
  35.         var cachecontrol = new CacheControlHeaderValue();
  36.         cachecontrol.MaxAge = TimeSpan.FromSeconds(_clientTimeSpan);        
  37.         cachecontrol.MustRevalidate = true;
  38.         return cachecontrol;
  39.     }
  40.     public override void OnActionExecuting(HttpActionContext ac)
  41.     {
  42.         if (ac != null)
  43.         {
  44.             if (_isCacheable(ac))
  45.             {
  46.                 _cachekey = string.Join(":"new string[] { ac.Request.RequestUri.AbsolutePath, ac.Request.Headers.Accept.FirstOrDefault().ToString() });
  47.                 if (WebApiCache.Contains(_cachekey))
  48.                 {
  49.                     var val = (string)WebApiCache.Get(_cachekey);
  50.                     if (val != null)
  51.                     {
  52.                         ac.Response = ac.Request.CreateResponse();
  53.                         ac.Response.Content = new StringContent(val);
  54.                         var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":responsect");
  55.                         if (contenttype == null)
  56.                             contenttype = new MediaTypeHeaderValue(_cachekey.Split(':')[1]);
  57.                         ac.Response.Content.Headers.ContentType = contenttype;
  58.                         ac.Response.Headers.CacheControl = setClientCache();
  59.                         return;
  60.                     }
  61.                 }
  62.             }
  63.         }
  64.         else
  65.         {
  66.             throw new ArgumentNullException("actionContext");
  67.         }
  68.     }
  69.         
  70.     public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContextactionExecutedContext)
  71.     {
  72.         if (!(WebApiCache.Contains(_cachekey)))
  73.         {
  74.             var body = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
  75.             WebApiCache.Add(_cachekey, body, DateTime.Now.AddSeconds(_timespan));
  76.             WebApiCache.Add(_cachekey + ":response-ct",actionExecutedContext.Response.Content.Headers.ContentType, DateTime.Now.AddSeconds(_timespan));
  77.         }
  78.         if (_isCacheable(actionExecutedContext.ActionContext))
  79.                 actionExecutedContext.ActionContext.Response.Headers.CacheControl = setClientCache();
  80.     }
  81. }

Step 9: Set action with attribute

We have finished the entire configuration, now we will set the attribute over the action. Here is the code of my Get() action within the Values controller.

  1. [WebApiOutputCache(120, 60, false)]  
  2. public string Get()  
  3. {  
  4.     return "Time is:-" + DateTime.Now.ToLongTimeString();  
  5. } 
Now if we browse the Get() action then we will get the current time from the server. And the time will remain unchanged from any request within 2 minutes.

Step 10: Output



Similar Articles