如何在输出缓存中使用动态持续时间值?

Dha*_*ari 6 output-caching asp.net-mvc-3

我正在使用ASP.NET MVC3.
我在控制器方法上使用了输出缓存.

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

我想在输出缓存中使用一些静态变量或其他东西来设置动态持续时间.

我怎样才能做到这一点?

nem*_*esv 11

我会从OutputCache属性继承并在那里设置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();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以Duration动态地和全局地改变CacheConfig.Duration

如果需要,您仍然可以覆盖每个操作的全局设置:

[MyOutputCache(Duration = 100, VaryByParam = "none")]
public ActionResult OtherAction()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)