Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Duration dynamically for ResponseCacheAttribute

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:

  • Configuring it in Response Caching Middleware, but then it applies to all controller actions.
  • Deriving from ResponseCacheAttribute does not work, as it's internal.

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 ?

like image 204
Silvos Avatar asked Dec 20 '25 04:12

Silvos


1 Answers

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.

like image 164
Lucas Avatar answered Dec 22 '25 00:12

Lucas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!