Here's a simple way if :
- Your basic goal is to be able to disable cache during debugging, and enable it during deployment
- You don't have complicated caching policies (that mean you truly need to respect Web.config's caching settings)
- You don't have a complicated deployment system that relies on Web.config's caching syntax
- Ideal if you're using XDT web transformations already
- You just assumed it would already work and are annoyed that it didn't and need a quick fix!
All I did was created a new attribute 'DonutCache'.
[DonutCache]
public ActionResult HomePageBody(string viewName)
{
var model = new FG2HomeModel();
return View(viewName, model);
}
I store my caching setting in Web.config (under a new custom name - so as to avoid confusion).
<appSettings>
<add key="DonutCachingDuration" value="5"/> <!-- debug setting -->
</appSettings>
I created a simple helper method to pull the value out.
public static class Config {
public static int DonutCachingDuration
{
get
{
return int.Parse(ConfigurationManager.AppSettings["DonutCachingDuration"]);
}
}
}
Unfortunately you can only initialize an [Attribute]
with a constant, so you need to initialize the attribute in its constructor (you cant just say [Attribute(Config.DonutCachingDuration)]
unfortunately).
Note: This doesn't prevent you setting 'varyByParam' in the [DonutCache] declaration - which is currently the only other property that is usable for caching of Action methods.
class DonutCacheAttribute : OutputCacheAttribute
{
public DonutCacheAttribute()
{
// get cache duration from web.config
Duration = Config.DonutCachingDuration;
}
}
Just use an XDT web transformation's and you're ready to deploy with a longer value.
<add key="DonutCachingDuration" value="120"
xdt:Locator="Match(key)" xdt:Transform="Replace"/>
Tip: You'll probably want to stick a @DateTime.Now.ToString()
in your partial view to make sure the cache setting is being respected.