ASP.NET MVC 4中使用OutputCacheAttribute实现有条件的缓存

5

我正在尝试实现我的操作结果的输出缓存。

在我的操作中,根据一些业务规则返回响应。在我的响应中,我发送错误代码。 如果有任何错误,我不希望缓存响应。

以下是操作结果:

  class Response 
  {
    public int ErrorCode { get; set; }
    public string Message { get; set; }

}


    [OutputCache(CacheProfile = "Test")]
    public ActionResult Sample()
    {
        Response response = new Response();
        return new JsonResult { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

我希望只在 ErrorCode==0 时缓存结果。

我尝试重写 OutputCache,但它不起作用。

 public class CustomOutputCacheAttribute : OutputCacheAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {

            if (filterContext.Result is JsonResult)
            {
                var result = (JsonResult)filterContext.Result;
                BaseReponse response = result.Data as BaseReponse;
                if (!response.IsSuccess)
                {
                    filterContext.HttpContext.Response.Cache.SetNoStore();
                }
                base.OnActionExecuted(filterContext);
            }
        }


    }

还有其他方法或方式可以实现这个吗。

谢谢


覆盖OutputCacheAttribute是正确的方法。您还可以在操作方法内手动缓存响应对象。 - Davor Zlotrg
更新了问题 - Ashwani K
为什么要自己实现错误响应对象?OutputCache 已经内置了对普通 HTTP 错误的支持... - Moeri
你能提供相关的参考资料吗? - Ashwani K
1个回答

3
你可以创建自己的自定义属性,根据结果错误代码来忽略 [OutputCache],就像这样:

您可以创建自定义属性来忽略[OutputCache],具体根据结果错误代码进行处理,例如:

[OutputCache(Duration=60, VaryByParam="none")]
[OutputCacheValidation]
public ActionResult Sample()
{
    var r = new Response();
    r.ErrorCode = 0;  
    return Json(r, JsonRequestBehavior.AllowGet);
}

public class OutputCacheValidationAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        base.OnResultExecuting(filterContext);
        filterContext.HttpContext.Response.Cache.AddValidationCallback(ValidatioCallback, filterContext.Result);
    }

    private static void ValidatioCallback(HttpContext context, object data, ref HttpValidationStatus validationStatus)
    {
        var jsonResult = data as JsonResult;
        if (jsonResult == null) return;

        var response = jsonResult.Data as Response;
        if (response == null) return;

        if (response.ErrorCode != 0)
        {
            //ignore [OutputCache] for this request
            validationStatus = HttpValidationStatus.IgnoreThisRequest;
            context.Response.Cache.SetNoServerCaching();
            context.Response.Cache.SetNoStore();
        }
    }
}

谢谢,不过它仍然将数据保存到缓存中,但在提供服务时进行验证。如果发生错误,我希望根本不要在缓存中存储数据。 - Ashwani K
我从你的代码和http://juristr.com/blog/2012/10/output-caching-in-aspnet-mvc/得到了灵感。现在它可以工作了。谢谢。 - Ashwani K

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