camilo888
camilo888

Reputation: 183

outputcache time instead of duration MVC

I want to cache the result of a method inside a Controller. The thing is that I want the cache to be erased every hour at :00. The duration="3600" is not an option, because if for instance the method is invoked for the first time at 3:20, the cache will last until 4:20 and I need it to be renewed at 4:00, because the database will be updated at this time and it is extremely important to keep this data up to date.

My web.config file right now is like this:

<caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <add name="1HourCacheProfile" varyByParam="*" enabled="true" duration="3600" location="Server" />
    </outputCacheProfiles>
  </outputCacheSettings>
</caching>

And I put this annotation before the method I want to be cached

[OutputCache(CacheProfile = "1HourCacheProfile")]

Does anyone knows how to achieve this?

Cheers

Upvotes: 1

Views: 1910

Answers (1)

camilo888
camilo888

Reputation: 183

Ok I already have a solution.

I made a class that inherits OutputCacheAttribute as I will show in this piece of code:

public class HourlyOutputCacheAttribute : OutputCacheAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        SetupDuration();
        base.OnActionExecuting(filterContext);
    }

    private void SetupDuration()
    {
        int seconds = getSeconds((DateTime.Now.Minute * 60) + DateTime.Now.Second, base.Duration);
        base.Duration -= seconds;            
    }

    private int getSeconds(int seconds, int duration)
    {
        if (seconds < duration)
            return seconds;
        else
            return getSeconds(seconds - duration, duration);
    }

}

And then I just put this Annotation in the method from the controller

    [HourlyOutputCache(VaryByParam = "*", Duration = 3600, Location = OutputCacheLocation.Server)]

And that's it... And I think you can use it with any divisor of 3600.

Any other better solution or comment is welcome :)

Upvotes: 1

Related Questions