Search code examples
asp.netasp.net-mvccachingoutputcache

Prevent output cache when the result is null


In my project I use the OutputCache attribute so my web server doesn't have to keep downloading the same files, but rarely there are some issues where for unknown reasons it returns null.

So If the result is null I don't want to cache the result is there a simple way to do this?

    [OutputCache(VaryByParam = "path", Duration = 6000)]
    public ActionResult LoadCachedFile(string path)
    {
        var result = DownloadFile(path);

        return result;
    }

Solution

  • I had to do something similar to what nikstffrs suggested, but instead of overriding OnActionExecuted I used OnResultExecuting.

    public class CustomOutputCache : OutputCacheAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if(!(filterContext.Result is EmptyResult))
               base.OnResultExecuting(filterContext);
        }
    }