【问题标题】:outputcache time instead of duration MVC输出缓存时间而不是持续时间 MVC
【发布时间】:2025-12-13 21:35:01
【问题描述】:

我想在控制器中缓存方法的结果。问题是我希望每小时在 :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")]

有谁知道如何做到这一点?

干杯

【问题讨论】:

  • 你需要通过代码手动设置缓存头来做到这一点,配置工具帮不了你

标签: asp.net-mvc caching controller outputcache


【解决方案1】:

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

我创建了一个继承 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 的任何除数一起使用。

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

【讨论】: