缓存ASP.NET MVC Web API结果

use*_*890 4 c# asp.net-mvc caching outputcache

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

由于缓存设置为1小时,我希望Web服务器为每个具有相同输入的请求保持返回相同的数字,而不再执行该方法.但事实并非如此,缓存属性没有效果.我做错了什么?

我使用MVC5,我从VS2015和IIS Express进行了测试.

Vla*_*mir 5

使用fiddler来查看HTTP响应 - 可能是响应头有:Cache-Control:没有缓存.

如果您使用Web API 2,那么:

使用Strathweb.CacheOutput.WebApi2可能是个好主意.然后你的代码是:

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

否则你可以尝试使用自定义属性

  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
          };
        }
      }
Run Code Online (Sandbox Code Playgroud)

然后

public class ValuesController : ApiController
{
   [CacheWebApi(Duration = 3600)]
    public int Get(int id)
      {
        return new Random().Next();
      }
}
Run Code Online (Sandbox Code Playgroud)