Caching ASP.NET MVC Web API Results

public class ValuesController : ApiController
{
   [System.Web.Mvc.OutputCache(Duration = 3600)]
   public int Get(int id)
   {
       return new Random().Next();
   }
}

Since caching is set to 1 hour, I expect the web server to return the same number for each request with the same input without re-executing the method. But this is not so, the caching attribute has no effect. What am I doing wrong?

I am using MVC5 and I have tested with VS2015 and IIS Express.

+4
source share
2 answers

With the help of a violinist, take a look at the HTTP response - perhaps the response header contains: Cache-Control: no cache.

If you are using Web API 2, then:

It is probably best to use Strathweb.CacheOutput.WebApi2. Then you will get the code:

public class ValuesController : ApiController
{
   [CacheOutput(ClientTimeSpan = 3600, ServerTimeSpan = 3600)]
    public int Get(int id)
      {
        return new Random().Next();
      }
}

else

  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
          };
        }
      }

public class ValuesController : ApiController
{
   [CacheWebApi(Duration = 3600)]
    public int Get(int id)
      {
        return new Random().Next();
      }
}
+5

VaryByParam - URL- -.

+2

Source: https://habr.com/ru/post/1653656/


All Articles