简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM