asp.net-core - 如何为 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 的硬编码值,但我需要以某种方式从配置中动态设置它。我已经尝试过:
- 在响应缓存中间件中配置它,但随后它适用于所有控制器操作。
- 从 ResponseCacheAttribute 派生不起作用,因为它是内部的。
有没有一种简单的方法来实现我想要的,还是我必须自己编写整个事情(自定义 ResponseCacheAtrribute + ResponseCacheFilter + ResponseCacheFilterExecutor)?
解决方案
我创建了一个新属性,它继承自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
}
这使我可以在我可能需要的特定时间进行构建。我尚未对此进行全面测试,但确认我在响应输出中看到了信息。
您应该能够将所需的任何参数或信息添加到属性中。
推荐阅读
- python - For and if in print python
- javascript - 如何在javascript中遍历对象数组并在其中找到相似的值?
- python - 在 shell 中执行某些操作时,我的 VSC 总是打开一个文件 - 如何防止这种情况发生?
- java - Maven:如何将 jar 放置或复制到另一个目录
- linux - 在 MacOS 上构建需要 net461 的 dotnet SDK 项目的最简单方法
- mysql - Mysql“错误1292(22007):截断不正确的时间值:'2355:46:39.000000'”在插入期间
- javascript - 使用 javascript 更改音频 src 时未播放 Chrome 网络音频
- mattermost - Mattermost 无法打开对话框
- java - 尝试创建服务类时出现 NullPointer 错误
- c# - 如何在 xamarin 表单中使用异步更改更改 ui