2

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Could you possibly go a little deeper on "returns the cached view when you hit the action"? I'm not following exactly what you mean. What cached view will it return at that point?
From MSDN: Represents an attribute that is used to mark an action method whose output will be cached. so would that be referring to what is being passed back to the view?
Yes. It could be a model with a list of feeds, for example. But in your case, the data is also being cached by HttpContext. Try to put the date in a viewbag instead.
I put the date inside of a view bag, and increased the duration to 10 seconds. as i refresh my web page, the time updates on each refresh. doesn't appear that the duration is working.
You shouldn't refresh. When you hit F5, the outputcache attribute doesn't work. It reloads everything. You should test with a link pointing to this specific action
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.