【问题标题】:Conditional Cache using OutputCacheAttribute in Asp.net MVC 4在 Asp.net MVC 4 中使用 OutputCacheAttribute 的条件缓存
【发布时间】:2015-02-18 06:36:50
【问题描述】:

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

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

跟随动作结果

  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 是正确的做法。您还可以在您的操作方法中手动缓存响应对象。
  • 更新问题
  • 为什么要实现自己的错误响应对象? OutputCache 内置了对正常 HTTP 错误的支持...
  • 你能提供同样的参考吗?

标签: asp.net-mvc asp.net-mvc-4 outputcache


【解决方案1】:

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

【讨论】:

  • 谢谢,但是它仍在将数据保存到缓存中,但在提供数据时会进行验证。如果发生错误,我想根本不将数据存储在缓存中
  • 我从您的代码和juristr.com/blog/2012/10/output-caching-in-aspnet-mvc 中得到了这个想法。现在它正在工作。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 2013-02-01
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-16
  • 2015-08-02
相关资源
最近更新 更多