Asp.net MVC 4 中使用 OutputCacheAttribute 的条件缓存

Conditional Cache using OutputCacheAttribute in Asp.net MVC 4

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

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

在操作结果中关注

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


    }

是否有任何其他方式或方法可以实现此目的。

谢谢

您可以创建自己的自定义属性,该属性将根据结果错误代码忽略 [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();
        }
    }
}