We help IT Professionals succeed at work.

asp.net remove item from cache if browser is closed

mugsey
mugsey used Ask the Experts™
on
I am setting something up in cache and want to ensure it is removed if a user does not log out but closes the browser window.

How can I ensure that
Cach.Remove("someKey");  

Is removed from the cach if the browser window is closed.

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Lead Software Engineer
Commented:
You are using the cache of IIS, you only can remove a key from cache if on the session_end in the global.asax.

Dont go with Cache, but with sessions, because sessions will automaticly remove after closing browser.

(This is not possible if you are using a session state server)
Top Expert 2013
Commented:
It might be tricky as no postback happens when browser is closed. So one way might be is to handle document unload event and do some ajax postback(don't have code handy), which again might be limited to certain browsers...
Some precautions you might take is setting cache expiration and Also if you might want to reset this cache upon the everytime the use log-in...

Author

Commented:
OK thanks

However this is a fix and I have to stay with cache.  Essentilly the app uses forms authentication and then stores some user properties in cache.

So if a user is logged in and closes browser window then the cache is still there.

So I can check is they are logged in on page load

ie

if (User.Identity.IsAuthenticated)

So I can build up some logic to say well if they are authenticated then fine but if not cach.remove("key")??
StephanLead Software Engineer
Commented:
You can use an slidingexpiration on the cache in order to remove it if the user is inactive for a while.

Author

Commented:
Sorry I did this in error I would like to award points amongst all answers equally

Author

Commented:
Sorry I did this in error I would like to award points amongst all answers equally
Robb HillSenior .Net Full Stack Developer

Commented:
time it out for those scenarios where a user doesnt log out...session state I believe defaults at 30 minutes...

the state can be managed as well however you want to configure...set it to be 5 minutes or so.