问题
I am having some issues understanding what is happening when I create a simple subclass of OutputCacheAttribute in MVC3. Here is the code:
public class ExampleOutputCacheAttribute : OutputCacheAttribute
{
public ExampleOutputCacheAttribute()
{
// breakpoint here
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// breakpoint here
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// breakpoint here
base.OnActionExecuted(filterContext);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// breakpoint here
base.OnResultExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
// breakpoint here
base.OnResultExecuted(filterContext);
}
}
The first time a controller action with this attribute is requested, the constructor and all overridden methods are hit, but if I refresh the page, none of the methods or the constructor are hit. It is as if the cache is being read from outside the OutputCacheAttribute, but looking at the MVC source code for OutputCacheAttribute, I can see that in OnActionExecuting, there is code for checking for a cached page and returning the result:
filterContext.Result = new ContentResult() { Content = cachedValue };
Can anyone shed any light on what is happening?
回答1:
It seems as though the OutputCache filter is more complicated than it originally appears. For page caching, it hooks in to the standard ASP.NET output caching mechanism which uses the OutputCacheModule HttpModule in IIS. Once the filter is hit once and adds the page to the cache, subsequent requests do not hit the filter in any way. The OutputCacheModule intercepts these requests and returns the cached object higher up the pipeline.
For action caching, a separate mechanism is used. This uses a static MemoryCache and the constructor and all overridden methods are hit on every request.
来源:https://stackoverflow.com/questions/7501299/subclassing-outputcache-issues-in-mvc3