Caching ChildActions using cache profiles won't work?

前端 未结 5 1622
粉色の甜心
粉色の甜心 2020-12-03 08:13

I\'m trying to use cache profiles for caching child actions in my mvc application, but I get an exception: Duration must be a positive number.

My web.config looks li

5条回答
  •  不思量自难忘°
    2020-12-03 08:41

    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).

    
           
    
    

    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.

      
    

    Tip: You'll probably want to stick a @DateTime.Now.ToString() in your partial view to make sure the cache setting is being respected.

提交回复
热议问题