65.9K
CodeProject is changing. Read more.
Home

Implement Caching in Web API

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (7 votes)

Oct 14, 2014

CPOL
viewsIcon

46654

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

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

Response in Chrome extension - XHR-Poster

Solution

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

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.

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

Response in Chrome extension - XHR-Poster