Question

In MVC an OutputCacheAttribute is capable to prevent the execution of the action it is decorating (if the relative cache exists)

How to implement the same mechanism with a custom attribute?

In other works I would like to be able to decorate an action, and based on a logic internal to the attribute it will decide whether the action should carry on executing or not.

Additions

I've implemented a mechanism by which if a request to an action arrives with a querystring like flushaction=flush_silent, the custom attribute (which is extending the OutputCacheAttribute) invalidates the cache.

What I would also like to do, is not to execute the Action:

[JHOutputCache(CacheProfile = "ContentPageController.Index")]
public ActionResult Index(string url)
{
     //custom code that should not execute when flushing the cache
}
Was it helpful?

Solution

As JHOutputCache extends OutputCacheAttribute, which derives from ActionFilterAttribute, halting execution of the underlying action is quite simple:

public class JHOutputCacheAttribute : OutputCacheAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (condition)
            filterContext.Result = new EmptyResult();
        else
            base.OnActionExecuting(filterContext);
    }
}

You can return any valid ActionResult here, including any custom ActionResult you may have derived.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top