代码之家  ›  专栏  ›  技术社区  ›  camilo888

输出缓存时间而不是持续时间MVC

  •  1
  • camilo888  · 技术社区  · 10 年前

    我想在Controller中缓存方法的结果。问题是,我希望缓存在每小时00点被删除。duration=“3600”不是一个选项,因为例如,如果在3:20第一次调用该方法,缓存将持续到4:20,我需要在4:00更新它,因为此时数据库将更新,保持数据最新非常重要。

    我的web.config文件现在是这样的:

    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="1HourCacheProfile" varyByParam="*" enabled="true" duration="3600" location="Server" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
    

    我把这个注释放在我想要缓存的方法之前

    [OutputCache(CacheProfile = "1HourCacheProfile")]
    

    有人知道如何做到这一点吗?

    干杯

    1 回复  |  直到 10 年前
        1
  •  1
  •   camilo888    10 年前

    好的,我已经有了解决方案。

    我创建了一个继承OutputCacheAttribute的类,如下面的代码所示:

    public class HourlyOutputCacheAttribute : OutputCacheAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            SetupDuration();
            base.OnActionExecuting(filterContext);
        }
    
        private void SetupDuration()
        {
            int seconds = getSeconds((DateTime.Now.Minute * 60) + DateTime.Now.Second, base.Duration);
            base.Duration -= seconds;            
        }
    
        private int getSeconds(int seconds, int duration)
        {
            if (seconds < duration)
                return seconds;
            else
                return getSeconds(seconds - duration, duration);
        }
    
    }
    

    然后我把这个注解放在控制器的方法中

        [HourlyOutputCache(VaryByParam = "*", Duration = 3600, Location = OutputCacheLocation.Server)]
    

    就这样…我想你可以用3600的除数。

    欢迎任何其他更好的解决方案或意见:)