I have a .Net Core 3.1 Web Api application and use the ResponseCache attribute on a controller action.
[HttpGet]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 30, VaryByQueryKeys = new[] { "id"})]
public string Get([FromQuery] int id)
{...}
While this is working fine with the hardcoded value for Duration, I need to set this dynamically from the config somehow. I already tried:
Is there a simple way to achieve what I want, or do I have to write the whole thing (custom ResponseCacheAtrribute + ResponseCacheFilter + ResponseCacheFilterExecutor) by myself ?
I make a new attribute which inherits from the ResponseCacheAttribute which adds most of what I need. For example -
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;
}
}
}
The Enum looks like
public enum ResponseCacheTime
{
Midnight
}
This allows me to build in specific times that I may need. I haven't fully tested this but confirmed I see the information in the response output.
You should be able to add any arguments or information you need into the attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With