Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Implement Caching in Web API

4.88/5 (7 votes)
14 Oct 2014CPOL 46.7K  
Output caching does not work for ASP.NET Web API. This tip is a solution to implement caching in web API.

Problem in Output Caching

If ASP.NET "OutputCache" added to rest method, "cache-control" in "Http Response Headers" always shows "no-cache".

Example

C#
public class ProductController : ApiController
{
    [OutputCache(Duration = 120)]
    public string Get(int id)
    {
        return "Product"+ 1;
    }
}

Response in Chrome extension - XHR-Poster

Image 1

Solution

It's easy to implement basic caching using "ActionFilterAttribute". We need to add cache control in OnActionExecuted methods as follows:

C#
public class CacheClientAttribute : ActionFilterAttribute
{
    public int Duration { get; set; }
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue
        {
            MaxAge = TimeSpan.FromSeconds(Duration),
            MustRevalidate = true,
            Public = true
        }
    }
}

Now, we can use this attribute in API method.

C#
public class ProductController : ApiController
{
     [CacheClient(Duration = 120)]
     public string Get(int id)
     {
         return "Product"+ 1;
     }
}

Response in Chrome extension - XHR-Poster

Image 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)