Mvc Donut Caching disable caching programmatically

665 views Asked by At

I'm using MvcDonutCaching on my project and looking for a way to disable caching globally to assist during debugging/testing.

I can't find any examples on how to achieve this in the documentation though I did find the CacheSettingsManager which exposes a IsCachingEnabledGlobally property however this is readonly.

The CacheSettingsManager doesn't have any constructors which would allow me to configure this setting either. Is there a way of configuring this setting?

There is an alternative solution which may work (ugly) but it's an absolute last resort and shouldn't really be necessary:

public class CustomOutputCache : DonutOutputCacheAttribute
{
    public CustomOutputCache()
    {
        if(ConfigurationManager.AppSettings["UseCache"] == "false")
        {
            base.NoStore = true;
            base.Duration = 0;
        }
    }
}

And then using this on my controller actions:

[CustomOutputCache]
public ActionResult Homepage() 
{
    // etc...
}

Is there a correct way to do this?

2

There are 2 answers

0
Erwin On

It is an ugly solution, but you could consider the use of compilation flags. Something like:

#if !DEBUG
[DonutOutputCache]
#endif      
public ActionResult Homepage() 
{
   // etc...
}

This will compile the attribute only when non-Debug configurations are selected.

0
Daniel Filipe On

In case anyone else stumbles upon this, add the below in your FilterConfig.cs

public class AuthenticatedOnServerCacheAttribute : DonutOutputCacheAttribute
{
    private OutputCacheLocation? originalLocation;

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {

        //NO CACHING this way
        if (ConfigurationManager.AppSettings["UseCache"] == "false")
        {
            originalLocation = originalLocation ?? Location;
            Location = OutputCacheLocation.None;
        }
        //Caching is on
        else
        {
            Location = originalLocation ?? Location;
        }

        base.OnResultExecuting(filterContext);
    }
}

You can now add this to your controllers.

    [AuthenticatedOnServerCache(CacheProfile = "Cache1Day")]
    public ActionResult Index()
    {
        return View();
    }

This answer was inspired by Felipe's answer here. https://stackoverflow.com/a/9694955/1911240