Tony D.
Tony D.

Reputation: 560

ASP.NET MVC - OutputCache - Does setting duration expire cached values?

Does setting the duration for OutputCache expire the cached values? Because if it does, I'm not seeing it.

[OutputCache(Duration = 1, Location = OutputCacheLocation.Client, VaryByParam = "none", NoStore = true)]
    public ActionResult Index()
    {
        if (System.Web.HttpContext.Current.Cache["time"] == null)
        {
            System.Web.HttpContext.Current.Cache["time"] = DateTime.Now;
        }
    }

I'm new to using OutputCache so excuse the beginner question. But it was my understanding that by specifying the duration, something was suppose to happen after the allotted time. In my code snippet above, the time persists regardless of when I refresh my view.

Upvotes: 2

Views: 1085

Answers (1)

Carlos Crespo
Carlos Crespo

Reputation: 256

You are confusing the OutputCache with the HttpContext.Current.Cache. The first is used to return the cached view when you hit the action, if the cache is not expired. And about that, you are right. Every 1 second it will return a new view.

However, the HttpContext.Current.Cache that you are filling with DateTime.Now, will never expire. Because you are not defining the absolute expiration

https://msdn.microsoft.com/en-us/library/system.web.caching.cache(v=vs.110).aspx

Doing this

System.Web.HttpContext.Current.Cache["time"] = DateTime.Now;

is the same as this

System.Web.HttpContext.Current.Cache.Insert("time", DateTime.Now, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration)

Use the Insert method and define the expiration properly, and it should work.

Upvotes: 1

Related Questions