Caching is the process of storing frequently used data or information in local memory for a specific time. When a client requests the same information, it will deliver the information from the local memory rather than the permanent data store. The primary benefit of caching is that it improves performance by reducing processing load.
Here are some approaches to implementing caching in a Web API.
1. HTTP Caching Headers - To control caching behaviour, use the built-in HTTP caching headers. These are the headings.
By setting appropriate caching headers in the API responses, clients and intermediary caches can cache the responses and avoid unnecessary requests to the server.
2. Output Caching - Use output caching to cache the entire response of a specific API endpoint. This approach saves the rendered output of the endpoint and serves it to subsequent requests without executing the entire request pipeline.
In ASP.NET Web API, you can use the OutputCache attribute to enable output caching for an action method or controller. You can specify cache duration, caching location, and other caching parameters using this attribute.
3. In-Memory Caching - Implement in-memory caching to store frequently accessed data or computed results. This approach is useful for caching data that is expensive to retrieve or compute. Libraries like MemoryCache in ASP.NET can be used to implement in-memory caching.
You can cache the data in memory for a specific duration or until it is invalidated. When a request is made, you can check if the data is available in the cache and return it directly, eliminating the need to fetch the data from the original source.
4. Distributed Caching - For scenarios where you have multiple instances of the API running or need to share the cache across different servers, you can use distributed caching solutions like Redis or Memcached. These caching systems allow you to store and retrieve cached data from a shared cache store accessible to all instances of the API.
For Example
In this example, we will see how to use caching in web API to improve its performance, by decreasing the response time. I have created a web API project. I have a "BlogController" and "Get" action Method, as per the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
namespace webapiExample.Controllers
{
public class BlogController : ApiController
{
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
public static List<Blog> blogList = new List<Blog>()
{
new Blog { Id = 1, Name="TutorialsTrend", Url="https://tutorialstrend.com/"},
new Blog { Id = 2, Name="StackOverflow", Url="http://stackoverflow.com/"},
new Blog { Id = 3, Name="StackOverflow", Url="http://CodeProject.com/"},
};
// GET api/Blog
public List Get()
{
return blogList;
}
}
}
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 1687 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 CustomCache. Just add a new class and rename it, as shown in the image below.
Now, inherit this class from ActionFilterAttribute .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http.Filters;
namespace webapiExample
{
public class CustomCache: ActionFilterAttribute
{
public int TimeDuration { get; set; }
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue
{
MaxAge = TimeSpan.FromSeconds(TimeDuration),
MustRevalidate = true,
Public = true
};
}
}
}
Now, add the TimeDuration attribute in the required controller, as follows. Here is my complete action method with highlighted TimeDuration=100.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
namespace webapiExample.Controllers
{
public class BlogController : ApiController
{
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
public static List<Blog> blogList = new List<Blog>()
{
new Blog { Id = 1, Name="TutorialsTrend", Url="https://tutorialstrend.com/"},
new Blog { Id = 2, Name="StackOverflow", Url="http://stackoverflow.com/"},
new Blog { Id = 3, Name="StackOverflow", Url="http://CodeProject.com/"},
};
[CustomCache(TimeDuration = 100)]
// GET api/Blog
public List Get()
{
return blogList;
}
}
}
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.
In this way, we can create a custom cache filter and apply it on the action method, in web API.