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