I would like the OutputCache
feature to be disabled if the system.web.compilation
setting in the web.config is set to debug="true"
.
I can successfully access this value by calling this method in my Global.asax's Application_Start()
:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
CompilationSection configSection = (CompilationSection)ConfigurationManager.GetSection("system.web/compilation");
if (configSection?.Debug == true)
{
filters.Add(new OutputCacheAttribute()
{
VaryByParam = "*",
Duration = 0,
NoStore = true
});
}
}
The problem is, any endpoints in my controllers that have OutputCache
explicitly set will not use the global filter that was set up.
[OutputCache(CacheProfile = "Month")]
[HttpGet]
public ViewResult contact()
{
return View();
}
Here is where that "Month" profile is defined in my web.config:
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="Month" duration="2592000" location="Any" varyByParam="*" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
I need to be able to nullify the use of explicitly defined OutputCache profiles, like "Month", when I'm in debugging mode. How can I do this?
@Back's answer is probably the most straight-forward solution that will work for the standard use case of wanting all caching disabled while debugging. However, because it is not a programmatic solution, I've come up with a way to do it all in code, which will also work for more advanced use cases.
First, we want to capture whether or not the app is in debugging mode when it is launched. We'll store that in a global variable to keep things speedy.
public static class GlobalVariables
{
public static bool IsDebuggingEnabled = false;
}
Then in the Global.asax code's Application_Start
method, write to the global property.
protected void Application_Start()
{
SetGlobalVariables();
}
private void SetGlobalVariables()
{
CompilationSection configSection = (CompilationSection)ConfigurationManager
.GetSection("system.web/compilation");
if (configSection?.Debug == true)
{
GlobalVariables.IsDebuggingEnabled = true;
}
}
Now we will create our own class to use for caching, which will inherit from OutputCacheAttribute
.
public class DynamicOutputCacheAttribute : OutputCacheAttribute
{
public DynamicOutputCacheAttribute()
{
if (GlobalVariables.IsDebuggingEnabled)
{
this.VaryByParam = "*";
this.Duration = 0;
this.NoStore = true;
}
}
}
Now when you decorate your controller endpoints for caching, simply use your new attribute instead of [OutputCache]
.
// you can use CacheProfiles or manually pass in the arguments, it doesn't matter.
// either way, no caching will take place if the app was launched with debugging
[DynamicOutputCache(CacheProfile = "Month")]
public ViewResult contact()
{
return View();
}