Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Cache using OutputCacheAttribute in Asp.net MVC 4

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

like image 515
Ashwani K Avatar asked Oct 20 '22 17:10

Ashwani K


1 Answers

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();
        }
    }
}
like image 173
Davor Zlotrg Avatar answered Oct 22 '22 23:10

Davor Zlotrg