Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 257
user256890 Avatar asked Sep 05 '16 09:09

user256890


2 Answers

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();
      }
}
like image 123
Vladimir Avatar answered Sep 21 '22 16:09

Vladimir


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.

like image 37
PhillipH Avatar answered Sep 22 '22 16:09

PhillipH