Implementing Caching In Web API

CACHING

Caching is a technique of storing frequently used data or information in a local memory, for a certain time period. So, next time, when the client requests the same information, instead of retrieving the information from the database, it will give the information from the local memory. The main advantage of caching is that it improves the performance by reducing the processing burden. 
 
Here, in this article, I will explain how to use caching in web API to improve its performance, by decreasing the response time. Here, I have created a web API project. I have a "DataController" and  "GetData" action Method, as per the following.
  1.       [AllowAnonymous]  
  2.       [Route("GetData")]   
  3.       public async Task<IHttpActionResult> getData()  
  4.       {  
  5.           Dictionary<objectobject> obj = new Dictionary<objectobject>();  
  6.           obj.Add("1""Punjab");  
  7.           obj.Add("2""Assam");  
  8.           obj.Add("3""UP");  
  9.           obj.Add("4""AP");  
  10.           obj.Add("5""J&K");  
  11.           obj.Add("6""Odisha");  
  12.           obj.Add("7""Delhi");  
  13.           obj.Add("9""Karnataka");  
  14.           obj.Add("10""Bangalore");  
  15.           obj.Add("21""Rajesthan");  
  16.           obj.Add("31""Jharkhand");  
  17.           obj.Add("41""chennai");  
  18.           obj.Add("51""jammu");  
  19.           obj.Add("61""Bhubaneshwar");  
  20.           obj.Add("71""Delhi");  
  21.           obj.Add("19""Karnataka");   
  22.           
  23.           return Ok(obj);    
  24.            
  25.   
  26.   
  27.       }  
Now, I will request the method from my PostMan Client, as shown below:



Now, if you check the Header section, you will get no-cache. 

 

We can see that it takes around 2449 miliseconds as my response time.

Now, we will use caching and see how we can reduce the response time of this request. For this, we have to create a custom filter. Just add a new class and rename it, as shown in the image below. 

 

Now, inherit this class from "ActionFilterAttribute" .
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http.Headers;  
  5. using System.Web;  
  6. using System.Web.Http.Filters;  
  7.   
  8. namespace Caching_In_API  
  9. {  
  10.     public class CacheFilter : ActionFilterAttribute  
  11.     {  
  12.         public int TimeDuration { getset; }  
  13.     public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)  
  14.     {  
  15.         actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue  
  16.         {  
  17.             MaxAge = TimeSpan.FromSeconds(TimeDuration),  
  18.             MustRevalidate = true,  
  19.             Public = true  
  20.         };  
  21.     }  
  22.     }  
  23. }  
Now, add the TimeDuration attribute in the required controller, as follows.

 

Here is my complete action method.
  1. [AllowAnonymous]  
  2.        [Route("GetData")]   
  3.        [CacheFilter(TimeDuration=100)]  
  4.        public async Task<IHttpActionResult> getData()  
  5.        {  
  6.            Dictionary<objectobject> obj = new Dictionary<objectobject>();  
  7.            obj.Add("1""Punjab");  
  8.            obj.Add("2""Assam");  
  9.            obj.Add("3""UP");  
  10.            obj.Add("4""AP");  
  11.            obj.Add("5""J&K");  
  12.            obj.Add("6""Odisha");  
  13.            obj.Add("7""Delhi");  
  14.            obj.Add("9""Karnataka");  
  15.            obj.Add("10""Bangalore");  
  16.            obj.Add("21""Rajesthan");  
  17.            obj.Add("31""Jharkhand");  
  18.            obj.Add("41""chennai");  
  19.            obj.Add("51""jammu");  
  20.            obj.Add("61""Bhubaneshwar");  
  21.            obj.Add("71""Delhi");  
  22.            obj.Add("19""Karnataka");   
  23.            
  24.            return Ok(obj);    
  25.             
  26.   
  27.   
  28.        }  
Now, run the application. On the first time, it will retrieve the data from the database. Later, it shows the information from local memory. Next, we see that the response time has decreased.

 
 
Now, if we check the header portion, we will see that the caching has been applied on it.



Thus, in this way, we can create a custom cache filter and apply it on the action method, in web API.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now