Conditional Cache using OutputCacheAttribute in Asp.net MVC 4

末鹿安然 提交于 2020-01-01 05:49:27

问题


I am trying to implement Output caching for my action results.

In my actions depending upon some business rules response is returned. In my response I send error code. I do not want to cache the response if there is any error.

Following in the Action Result

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

I want cache the Result only if ErrorCode==0.

I tried overriding OutputCache, but it is not working

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


    }

Is there any other way or approach to achieve this.

Thanks


回答1:


You can create your own custom attribute that will ignore [OutputCache] based on the result error code, something like this:

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


来源:https://stackoverflow.com/questions/28577455/conditional-cache-using-outputcacheattribute-in-asp-net-mvc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!