返回Json的动作上的OutputCache属性不起作用--当我多次在浏览器中单击动作URL时,每次在VS2012中激活断点(看起来OutputCache属性被忽略了)。这是我的代码:
public class ApiController : GenericControllerBase
{
[OutputCache(Duration = 300, VaryByParam = "type;showEmpty;sort;platform")]
public JsonResult GetCategories(string type, bool? showEmpty, string sort, string platform)
{
///... creating categoryResults object
return Json(new ApiResult() { Result = categoryResults }, JsonRequestBehavior.AllowGet);
}
} GenericControllerBase继承自Controller。在其他从GenericControllerBase继承的控制器中,OutputCache按预期工作,但它们返回View()而不是Json。作为一个实验,我添加了VaryByCustom参数,并检查global.asax文件中的GetVaryByCustomString方法也没有被击中,因此缓存功能被完全忽略了。我使用MVC3和autofac进行服务注入(但其他使用autofac注入的控制器与OutputCache工作正常)。
有什么问题吗?什么能阻止OutputCache功能?它有可能与缓存整个响应有关吗?在我的项目中使用OutputCache的所有其他操作都是嵌入了@Html.Action(.)的部分操作。在视野中。
在MVC3中缓存整个Json响应的最佳方法是什么?
更新
经过一些测试,结果发现返回完整页面的操作(不仅仅是json)忽略了OutputCache。缓存只适用于我的项目中的子操作。可能是什么原因?
发布于 2013-01-17 11:34:10
最后,我为MVC3使用了一个解决方案,忽略了OutputCache属性。我使用自定义操作筛选器进行缓存:
public class ManualActionCacheAttribute : ActionFilterAttribute
{
public ManualActionCacheAttribute()
{
}
public int Duration { get; set; }
private string cachedKey = null;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string key = filterContext.HttpContext.Request.Url.PathAndQuery;
this.cachedKey = "CustomResultCache-" + key;
if (filterContext.HttpContext.Cache[this.cachedKey] != null)
{
filterContext.Result = (ActionResult)filterContext.HttpContext.Cache[this.cachedKey];
}
else
{
base.OnActionExecuting(filterContext);
}
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Cache.Add(this.cachedKey, filterContext.Result, null, DateTime.Now.AddSeconds(Duration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
base.OnActionExecuted(filterContext);
}
}上面的属性根据给定时间的精确URL路径和查询缓存请求,并且按预期工作。
https://stackoverflow.com/questions/14265839
复制相似问题