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进行了测试。
答案 0 :(得分:5)
使用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();
}
}
答案 1 :(得分:2)
您需要使用属性的VaryByParam部分 - 否则只有没有查询字符串的URL部分才会被视为缓存键。