首页 > 解决方案 > 如何为 ResponseCacheAttribute 动态设置 Duration

问题描述

我有一个 .Net Core 3.1 Web Api 应用程序并在控制器操作上使用 ResponseCache 属性。

[HttpGet]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 30, VaryByQueryKeys = new[] { "id"})]
public string Get([FromQuery] int id)
{...}

虽然这适用于 Duration 的硬编码值,但我需要以某种方式从配置中动态设置它。我已经尝试过:

有没有一种简单的方法来实现我想要的,还是我必须自己编写整个事情(自定义 ResponseCacheAtrribute + ResponseCacheFilter + ResponseCacheFilterExecutor)?

标签: asp.net-coreasp.net-core-webapiasp.net-core-3.1

解决方案


我创建了一个新属性,它继承自ResponseCacheAttribute添加了我需要的大部分内容。例如 -

    public class ResponseCacheTillAttribute : ResponseCacheAttribute
    {
        public ResponseCacheTillAttribute(ResponseCacheTime time = ResponseCacheTime.Midnight)
        {
            DateTime today = DateTime.Today;
            switch (time)
            {
                case ResponseCacheTime.Midnight:
                    DateTime midnight = today.AddDays(1).AddSeconds(-1);
                    base.Duration = (int)(midnight - DateTime.Now).TotalSeconds;
                    break;
                default:
                    base.Duration = 30;
                    break;
            }
        }
    }

枚举看起来像

    public enum ResponseCacheTime
    {
        Midnight
    }

这使我可以在我可能需要的特定时间进行构建。我尚未对此进行全面测试,但确认我在响应输出中看到了信息。

您应该能够将所需的任何参数或信息添加到属性中。


推荐阅读