CR41G14
CR41G14

Reputation: 5594

Custom output cache mvc4

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

Upvotes: 0

Views: 245

Answers (1)

adricadar
adricadar

Reputation: 10209

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)]

Upvotes: 1

Related Questions