I\'m trying to cache the output of an ApiController method in Web API.
Here\'s the controller code:
public class TestController : ApiController
{
I am very late, but still thought to post this great article on Caching in WebApi
https://codewala.net/2015/05/25/outputcache-doesnt-work-with-web-api-why-a-solution/
public class CacheWebApiAttribute : ActionFilterAttribute
{
public int Duration { get; set; }
public override void OnActionExecuted(HttpActionExecutedContext filterContext)
{
filterContext.Response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(Duration),
MustRevalidate = true,
Private = true
};
}
}
In the above code, we have overridden OnActionExecuted method and set the required header in the response. Now I have decorated the Web API call as
[CacheWebApi(Duration = 20)]
public IEnumerable Get()
{
return new string[] { DateTime.Now.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString() };
}