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.

1

2 Answers 2

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();
      }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I went with the custom attribute. Works very well. Thanx!
glad I could help )
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.