Output caching for an ApiController (MVC4 Web API)

后端 未结 5 1309
我在风中等你
我在风中等你 2020-12-04 23:41

I\'m trying to cache the output of an ApiController method in Web API.

Here\'s the controller code:

public class TestController : ApiController
{
            


        
5条回答
  •  無奈伤痛
    2020-12-05 00:24

    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
    ...
    

提交回复
热议问题