Mvc Donut Caching programmatically disable caching

I am using MvcDonutCaching in my project and am looking for a way to disable caching globally to help during debugging / testing.

I can't find examples of how to do this in the documentation, but I did find CacheSettingsManager

one that provides a property IsCachingEnabledGlobally

, but this readonly

.

There CacheSettingsManager

are no constructors that would allow me to customize this parameter. Is there a way to tweak this setting?

There is an alternative solution that might work (ugly), but this is 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?

+3


source to share


2 answers


This is an ugly solution, but you might consider using compilation flags. Something like:

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

      



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

0


source


If anyone else stumbles upon this please add below to 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);
    }
}

      

Now you can add this to your controllers.



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

      

This answer was inspired by Felipe 's answer . fooobar.com/questions/338621 / ...

0


source







All Articles