asp.net - deleting cache object at session end

1.7k Views Asked by At

I have a wrapper class for Caching (CachingBL) where I store users that are currently signed in (some of their session info).

In CachingBL wrapper there is actually a dictionary of users, and I am putting that dictionary in cache like this: HttpContext.Current.Cache.Insert(...):

At the session end I would need to access to the cache like this:

var cacheBL = (CacheBL)HttpContext.Current.Cache.Get("MyCache_CacheSlot");

But the problem is that HttpContext.Current is empty, so I cannot access the Cache object. The Cache itself is not empty (tested), but I can't figure out how to access it at Session_End.

4

There are 4 best solutions below

1
On

Instead of putting the whole dictionary in the cache as one cache entry, put each element in the cache as an entry. Then you can give each element a sliding time window of the session timeout time, and let the system handle expiration.

0
On

Inside the Session_OnEnd event there is no way to get access to the HttpContext.Current because there is no current request.

But you do have access to the session state which includes all session variables. So if you us a session variable to store your token to the key name of the sessions cache slot ("MyCache_CacheSlot" in your example), you will be able to release that cache inside the Session_OnEnd event.

0
On

You can use System.Web.HttpRuntime.Cache to access the cache statically.

1
On

System.Web.SessionState.HttpSessionState is the one I should use instead of HttpContext.Current