I\'m trying to cache the output of an ApiController method in Web API.
Here\'s the controller code:
public class TestController : ApiController
{
The answer of Aliostad states that Web API turns off caching, and the code of HttpControllerHandler shows that it does WHEN response.Headers.CacheControl is null.
To make your example ApiController Action return a cacheable result, you can:
using System.Net.Http;
public class TestController : ApiController
{
public HttpResponseMessage Get()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(System.DateTime.Now.ToString());
response.Headers.CacheControl = new CacheControlHeaderValue();
response.Headers.CacheControl.MaxAge = new TimeSpan(0, 10, 0); // 10 min. or 600 sec.
response.Headers.CacheControl.Public = true;
return response;
}
}
and you will get a HTTP response header like this:
Cache-Control: public, max-age=600
Content-Encoding: gzip
Content-Type: text/plain; charset=utf-8
Date: Wed, 13 Mar 2013 21:06:10 GMT
...