Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

People also ask

What is the difference between session clear and session abandon?

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.

Which method is used to clear the session values?

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

What is session abandon ()?

The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.


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 the user to relogin for example) and reset all the session specific data.


Only using Session.Clear() when a user logs out can pose a security hole. As the session is still valid as far as the Web Server is concerned. It is then a reasonably trivial matter to sniff, and grab the session Id, and hijack that session.

For this reason, when logging a user out it would be safer and more sensible to use Session.Abandon() so that the session is destroyed, and a new session created (even though the logout UI page would be part of the new session, the new session would not have any of the users details in it and hijacking the new session would be equivalent to having a fresh session, hence it would be mute).


Session.Abandon destroys the session as stated above so you should use this when logging someone out. I think a good use of Session.Clear would be for a shopping basket on an ecommerce website. That way the basket gets cleared without logging out the user.