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.
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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With