1

I have an ASP .NET MVC 4 application. I'd like to return cache-control response header with no-store set by default for all actions and allow some exceptions for ceratin endpoints if they were to cache results. To achieve this I've tried to register OutputCacheAttribute at Application_Start() for all actions with NoStore property set to true. Then I could overwrtie global settings by decorating controllers or actions with OutputCacheAttribute if I wanted them to cache results. Below is the simplified code sample from my app. I've based everything on this post https://forums.asp.net/t/2146531.aspx?Disable+cache+in+ASPNET+MVC.

public class MvcApplication : System.Web.HttpApplication
{
   protected MvcApplication() : base()
   {
   }
 
   protected void Application_Start()
   {
      GlobalFilters.Filters.Add(new OutputCacheAttribute
      {
         VaryByParam = "*",
         Duration = 0,
         NoStore = true,
      });
   }
        
}

However when I enter views that consist of partial views the application throws the following exception: enter image description here

Why should I set the duration if I don't even want to cache results? Also it looks like child actions don't support passing NoStore property: Asp.Net MVC 3 Partial Page Output Caching Not Honoring Config Settings

I've also tried to make my own action filter and it seems to work but I don't like this approach very much, and I don't event know if it would be possible to override my custom attribute on controller or action levels:

public class NoCacheGlobalAttribute : ActionFilterAttribute
{
   public override void OnResultExecuted(ResultExecutedContext filterContext)
   {
      var cache = filterContext.HttpContext.Response.Cache;
      cache.SetNoStore();
      cache.SetMaxAge(TimeSpan.FromSeconds(0));
   }
}

Is there any way I could make use of existing OutputCacheAttribute in the way I described above? I want to disable caching for all actions by default and be able to enable caching for certain endpoints if I want to. If not, have you got any other tips?

Alienown
  • 137
  • 2
  • 9

1 Answers1

0

Add your custom filter to the global filters

GlobalFilters.Filters.Add(new NoCacheGlobalAttribute());
vimuth
  • 5,064
  • 33
  • 79
  • 116
Luis
  • 1