7

So I am working on a project which uses ASP.NET. I am trying to call Cache["key"] but the compiler complains about how System.Web.Caching.Cache is "nat valid at this point".

If I call Cache obj = new Cache(); the obj is always null.

I can access HttpContext.Current.Cache - but this doesnt let me specify an absolute expiration and sliding expiration in the Insert() method.

Can someone help me?

Ash
  • 24,276
  • 34
  • 107
  • 152

2 Answers2

14

You should be able to absolute or sliding expiration calling the insert on HttpRuntime.Cache. It has several overloads. Ex:

HttpRuntime.Cache.Insert("EXAMPLE_KEY", 
                        exampleItem, 
                        Nothing,                           
                        DateTime.Now.AddHours(1),
                        System.Web.Caching.Cache.NoSlidingExpiration);

The exact same code should also work with HttpContext.Current.Cache.

Jim Petkus
  • 4,500
  • 25
  • 19
  • Can't have an absolute expiration AND a sliding expiration? It seems like it one or the other. – Ash Feb 10 '09 at 04:33
  • I am not sure how that would work, the two forms of expiration would surely contradict each other at some point. For this reason it is not allowed. One value should be supploed and the other should be System.Web.Caching.Cache.NoSlidingExpiration and System.Web.Caching.Cache.NoAbsoluteExpiration. – Jim Petkus Feb 10 '09 at 13:50
  • According to [this](https://stackoverflow.com/questions/863654/difference-between-httpruntime-cache-and-httpcontext-current-cache) there's no real benefit for using HttpContext.Current.Cache instead of HttpRuntime.Cache, so the code example you posted should suffice anyway. – BornToCode Aug 06 '18 at 18:15
0

I suggest you to try PCache class under PokeIn library. Even if you use FREE edition of that library, there is no limitation with this class. It has many more functionalities in comparison to ASP.NET Cache class and you dont have to deal with these problems. there is a simple sample project available on the web site.

Zuuum
  • 1,495
  • 11
  • 18