I have a global NoCache filter as shown here: https://stackoverflow.com/a/12964123/78739
This global no cache filter applies to all actions. I have a case where I need to allow caching for one particular action using OutputCacheAttribute. I was thinking in the NoCache filter I would check to see if the action that has just executed has the OutputCacheAttribute. If it does, it does NOT apply the no cache settings. So for example, my code would be:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class NoCacheAttribute : FilterAttribute, IResultFilter
{
public void OnResultExecuted(ResultExecutedContext filterContext)
{
if (/* action does not have OutputCacheAttribute */)
{
var cache = filterContext.HttpContext.Response.Cache;
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetRevalidation(HttpCacheRevalidation.ProxyCaches);
cache.SetExpires(DateTime.Now.AddYears(-5));
cache.AppendCacheExtension("private");
cache.AppendCacheExtension("no-cache=Set-Cookie");
cache.SetProxyMaxAge(TimeSpan.Zero);
}
}
}
The problem is I don't know how to get the action and its attributes from the ResultExecutedContext variable that is passed into the OnResultExecuted method.
The ActionFilterAttribute is the base class for all the attribute filters. It provides the following methods to execute a specific logic after and before controller action's execution: OnActionExecuting(ActionExecutingContext filterContext): Just before the action method is called.
Filter actions send information between worksheets. Typically, a filter action sends information from a selected mark to another sheet showing related information. Behind the scenes, filter actions send data values from the relevant source fields as filters to the target sheet.
Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns. Result filters contain logic that is executed before and after a view result is executed.
This answer is for MVC4 since MVC5 has filter overrides
There doesn't seem to be a clean way (I avoid reflection. Yuck!) to get the ActionDescriptor
from OnResultExecuted
Contrary to the non-accepted answer in SO link you gave, OutputCacheAttribute does control client cache so:
in the global
filters.Add(new OutputCacheAttribute { Location = OutputCacheLocation.None, NoStore = true });
Then in the action
//The OutputCacheAttribute in the global filter won't be called
//Only this OutputCacheAttribute is called since AllowMultiple in OutputCacheAttribute is false
[[OutputCacheAttribute(Location = OutputCacheLocation.Server, Duration = 100)]
public ActionResult Index()
{
return View();
}
Check the response headers to verify
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With