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?

5
  • 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 that has a parameter for a 'property name' - [OutputCache(Duration = "myDurationProperty"] and use reflection to get the value of the property Commented Mar 22, 2018 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. Commented Mar 22, 2018 at 23:00
  • Yes, but it would be the same principal as I noted above. You could add a series of <outputCacheProfiles><name="xxx" duration="20"> 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) Commented Mar 22, 2018 at 23:11
  • See this post: stackoverflow.com/questions/10426843/… Commented Mar 23, 2018 at 6:32
  • Possible duplicate of How to use dynamic duration value in Output Caching? Commented Mar 23, 2018 at 14:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.