Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is OutputCache a result filter and not an action filter in ASP.NET MVC?

The OutputCache attribute is commonly given as an example of a result filter in ASP.NET MVC. This MSDN page is one place. As such it wraps execution of the ActionResult object. But isn't that object executed at the end of the action method? I'm confused as to how it allows a cached response to be used and prevents the action itself from executing if it only wraps execution of the ActionResult at the end of that method. I know that caching works, so there is clearly some obvious piece that I'm missing.

like image 444
regularmike Avatar asked May 29 '14 21:05

regularmike


1 Answers

The OutputCacheAttribute inherits from ActionFilterAttribute, which in turn implements IActionFilter, and IResultFilter. Thus the OutputCacheAttribute is both an action filter and a result filter.

When you think about it, this makes perfect sense. The logic behind a cache goes like this:

  1. On execution
    • Is the item in the cache?
    • If Yes : return from cache (done)
    • If No, continue
  2. Get result
  3. On exiting
    • put in cache
    • return result

So part 1 is handled by the implementation of IActionFilter, if that doesn't immediately return a result, we continue with the action and the implementation of IResultFilter handles adding that result to the cache for future calls.

Thanks to ASP.NET being open source, this can be confirmed in code. Check out OutputCacheAttribute.cs on codeplex.

  • Line 222 is where the cahce is checked during OnActionExecuting (part of IActionFilter)

  • Line 237 - 249 the OnActionExecuting method sets up a callback that gets invoked during OnResultExecuted (part of IResultFilter)

like image 106
Simon C Avatar answered Sep 20 '22 12:09

Simon C