首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不适用于JsonResult的Outputcache (asp.net-mvc-3)

不适用于JsonResult的Outputcache (asp.net-mvc-3)
EN

Stack Overflow用户
提问于 2013-01-10 19:34:23
回答 1查看 2.3K关注 0票数 1

返回Json的动作上的OutputCache属性不起作用--当我多次在浏览器中单击动作URL时,每次在VS2012中激活断点(看起来OutputCache属性被忽略了)。这是我的代码:

代码语言:javascript
复制
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。缓存只适用于我的项目中的子操作。可能是什么原因?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-17 11:34:10

最后,我为MVC3使用了一个解决方案,忽略了OutputCache属性。我使用自定义操作筛选器进行缓存:

代码语言:javascript
复制
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路径和查询缓存请求,并且按预期工作。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14265839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档