How to use dynamic duration value in Output Caching?
Asked Answered
H

1

6

I'm using ASP.NET MVC3.
I've used Output Caching on controller method.

   [OutputCache(Duration = 3660, VaryByParam = "none")]
   public ActionResult Index()
   {
       some code;
       return View();
   }

I want to put dynamic duration using some static variable or something else in Output Caching.

How can i do this?

Hydrolyte answered 3/5, 2012 at 7:20 Comment(0)
T
11

I would inherit from the OutputCache attribute and set there the Duration:

public static class CacheConfig
{
    public static int Duration = 36600;
}

public class MyOutputCacheAttribute : OutputCacheAttribute
{
    public MyOutputCacheAttribute()
    {
        this.Duration = CacheConfig.Duration;
    }
}

[MyOutputCache(VaryByParam = "none")]
public ActionResult Index()
{
    return View();
}

Then you can change the Duration dynamically and globally trough the CacheConfig.Duration

And you can still override the global setting on every action if you want:

[MyOutputCache(Duration = 100, VaryByParam = "none")]
public ActionResult OtherAction()
{
    return View();
}
Tameika answered 3/5, 2012 at 7:28 Comment(1)
Won't work, attributes are instantiated only ONCE, changing CacheConfig.Duration at runtime won't magically re-execute your constructorClaimant

© 2022 - 2024 — McMap. All rights reserved.