ASP.NET MVC Web API结果的缓存

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

由于缓存设置为1小时,我希望在不重新执行方法的情况下,Web服务器对于相同输入的每个请求都返回相同的数字。但事实并非如此,缓存属性没有效果。我做错了什么?

我使用MVC5,并从VS2015和IIS Express进行测试。


https://codewala.net/2015/05/25/outputcache-doesnt-work-with-web-api-why-a-solution/ - Saurabh Chauhan
2个回答

10

使用 Fiddler 查看 HTTP 响应 - 可能响应头包含:Cache-Control: no cache

如果你在使用 Web API 2,则:

使用 Strathweb.CacheOutput.WebApi2 可能是一个不错的选择。那么你的代码将会是:

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

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

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

然后

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

我选择了自定义属性。效果非常好。谢谢! - user256890
很高兴能够帮助到您 ) - Vladimir

2

您需要使用Attribute的VaryByParam部分 - 否则只有URL部分而没有查询字符串将被视为缓存键。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接