Click here to Skip to main content
14,825,830 members
Articles / Web Development / ASP.NET
Tip/Trick
Posted 14 Oct 2014

Tagged as

Stats

41.2K views
22 bookmarked

Implement Caching in Web API

Rate me:
Please Sign up or sign in to vote.
4.88/5 (7 votes)
14 Oct 2014CPOL
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)

Share

About the Author

Jnana
Software Developer
India India
No Biography provided

Comments and Discussions

 
QuestionI think you're confusing server-side caching with and client-side caching Pin
PeterTheSwede15-Oct-14 2:13
MemberPeterTheSwede15-Oct-14 2:13 
AnswerOutputCache attribute Pin
Mario Majčica15-Oct-14 2:12
professionalMario Majčica15-Oct-14 2:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.