In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?
Session.Abandon() destroys the session
and the Session_OnEnd event is
triggered.
Session.Clear() just removes all
values (content) from the Object. The
session with the same key is still
alive.
So, if you use Session.Abandon(), you
lose that specific session and the
user will get a new session key. You
could use it for example when the user
logs out.
Use Session.Clear(), if you want that
the user remaining in the same session
(if you don't want him to relogin for
example) and reset all his session
specific data.
What is the difference between Session.Abandon() and Session.Clear()
Clear - Removes all keys and values
from the session-state collection.
Abandon - removes all the objects
stored in a Session. If you do not
call the Abandon method explicitly,
the server removes these objects and
destroys the session when the session
times out. It also raises events like
Session_End.
Session.Clear can be compared to
removing all books from the shelf,
while Session.Abandon is more like
throwing away the whole shelf.
...
Generally, in most cases you need to
use Session.Clear. You can use
Session.Abandon if you are sure the
user is going to leave your site.
So back to the differences:
- Abandon raises Session_End request.
- Clear removes items immediately, Abandon does not.
- Abandon releases the SessionState object and its items so it can garbage
collected.
- Clear keeps SessionState and resources associated with it.
Session.Clear() or Session.Abandon() ?
You use Session.Clear() when you don't
want to end the session but rather
just clear all the keys in the session
and reinitialize the session.
Session.Clear() will not cause the
Session_End eventhandler in your
Global.asax file to execute.
But on the other hand
Session.Abandon() will remove the
session altogether and will execute
Session_End eventhandler.
Session.Clear() is like removing books
from the bookshelf
Session.Abandon() is like throwing the
bookshelf itself.
Question
I check on some sessions if not equal null in the page load. if one of them equal null i wanna to clear all the sessions and redirect to the login page?
Answer
If you want the user to login again, use Session.Abandon.