Caching of ASP.NET MVC Web API results
Asked Answered
S

2

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

Since caching is set for 1 hour, I would expect the web server keeps returning the same number for every request with the same input without executing the method again. But it is not so, the caching attribute has no effect. What do I do wrong?

I use MVC5 and I conducted the tests from VS2015 and IIS Express.

Sparoid answered 5/9, 2016 at 9:8 Comment(1)
codewala.net/2015/05/25/…Etymology
R
10

Use a fiddler to take a look at the HTTP response - probably Response Header has: Cache-Control: no cache.

If you using Web API 2 then:

It`s probably a good idea to use Strathweb.CacheOutput.WebApi2 instead. Then you code would be:

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

else you can try to use custom attribute

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

and then

public class ValuesController : ApiController
{
   [CacheWebApi(Duration = 3600)]
    public int Get(int id)
      {
        return new Random().Next();
      }
}
Redmon answered 5/9, 2016 at 9:34 Comment(2)
I went with the custom attribute. Works very well. Thanx!Sparoid
glad I could help )Redmon
B
2

You need to use the VaryByParam part of the Attribute - otherwise only the URL part without the query string will be considered as a cache key.

Brendonbrenk answered 5/9, 2016 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.