0
  • ASP.NET 4.61
  • MVC 5

I want to know if it is possible to add output caching to an MVC application at runtime and vary it.

So normally one would declare an output cache attribute as follows:

[OutputCache(Duration = 10]  
public ActionResult MyAction()  
{  
}

What I want to be able to do is to selectively enable and disable output caching on actions at runtime. So if I started out with a deployed application:

public ActionResult One()  
{  
}

public ActionResult Two()  
{  
}

and at runtime I decided I wanted Two() to be cached as if I had:

[OutputCache(Duration = 20]  
public ActionResult MyAction()  
{  
}

but then later I want it to be:

[OutputCache(Duration = 50]  
public ActionResult MyAction()  
{  
}

and then later remove caching all together:

public ActionResult MyAction()  
{  
}

So my question are:

1) Is it possible to control the caching of a controller method at runtime ie. Apply the equivalence of [OutputCache] at runtime? 2) Is there a different (easy) way to vary output caching at runtime?

TheEdge
  • 9,291
  • 15
  • 67
  • 135
  • Attributes are metadata and the values must be known at compile time, so short answer is no. However one (not easy) option would be to create you own attribute (based on the [source code](https://github.com/mono/aspnetwebstack/blob/master/src/System.Web.Mvc/OutputCacheAttribute.cs) that has a parameter for a 'property name' - `[OutputCache(Duration = "myDurationProperty"]` and use reflection to get the value of the property –  Mar 22 '18 at 22:45
  • @StephenMuecke Based on that I could perhaps make a custom attribute where I could vary the "CacheProfile" property at runtime. At least then I could pre-define certain "cache rulesets". And as long as I had enough of those and did not have to change the web.config then we would be pretty much sorted. – TheEdge Mar 22 '18 at 23:00
  • Yes, but it would be the same principal as I noted above. You could add a series of `` etc to you web config. But then you would still need to define a custom attribute that specifies the name of a property that contains the value for the profile name to use (and use reflection to retrieve it) –  Mar 22 '18 at 23:11
  • See this post: https://stackoverflow.com/questions/10426843/how-to-use-dynamic-duration-value-in-output-caching – Hooman Bahreini Mar 23 '18 at 06:32
  • Possible duplicate of [How to use dynamic duration value in Output Caching?](https://stackoverflow.com/questions/10426843/how-to-use-dynamic-duration-value-in-output-caching) – Agnel Amodia Mar 23 '18 at 14:13

0 Answers0