0

I am trying to utilise caching on an MVC4 project and I have the following attribute set on my homepage:

[OutputCache(Location=OutputCacheLocation.ServerAndClient,Duration=14400)]

This works fine, however the duration is causing me an issue. What I need is for the cache to expire on the start of a new day (midnight each day). I could set the duration to be 24 hours however this does not solve my problem with my page having new content on the start of each day. I have explored the vary by param method and I understand that I can append the date to the URL but this is very messy. Does anyone know an alternative?

Thanks in advance

CR41G14
  • 5,464
  • 5
  • 43
  • 64
  • It sounds like you mean [cache invalidation](http://stackoverflow.com/questions/16194140/how-to-invalidate-cache-data-outputcache-from-a-controller)? – jdphenix Apr 18 '15 at 05:47

1 Answers1

1

A solution will be to extend the OutputCacheAttribute and to create a new one that works for midnight because you can set Duration in constructor.

public class OutputCacheMidnightAttribute : OutputCacheAttribute
{
    public OutputCacheMidnightAttribute()
    {
        // remaining time to midnight
        Duration = (int)((new TimeSpan(24, 0, 0)) - DateTime.Now.TimeOfDay).TotalSeconds;
    }
}

And you use it like this

[OutputCacheMidnight(Location=OutputCacheLocation.ServerAndClient)]
adricadar
  • 9,971
  • 5
  • 33
  • 46