In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?
Solution 1
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.
Solution 2
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).
Solution 3
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.
Lance Fisher
Missoula .NET Users Group Founder Father Husband Ultra runner Believer Snowboarder Math Geek Learning Russian Learning Spanish
Updated on May 05, 2020Comments
-
Lance Fisher about 4 years
Both Session.Clear() and Session.Abandon() get rid of session variables. As I understand it, Abandon() ends the current session, and causes a new session to be created thus causing the End and Start events to fire.
It seems preferable to call Abandon() in most cases, such as logging a user out. Are there scenarios where I'd use Clear() instead? Is there much of a performance difference?
-
Trisped almost 12 yearsWhat would be the point of hijacking an empty session? The hijacker would still have to log in, and their is no data to accidently provide to the new user.
-
Bibhu over 11 yearsI believe better to use RemoveAll() instead of Clear(), as "Darin Dimitrov" has suggested over here stackoverflow.com/a/3931344/713246
-
Adam Miller about 10 years@Bibhu: How did he suggest that RemoveAll() was better than Clear()? All I saw in his answer was that RemoveAll() calls Clear(), and seems to be functionally identical.
-
brichins over 9 yearsJust used
Session.Abandon()
as a 'logout' on an internal app using Windows Authentication - users did not have to re-authenticate (Chrome, FF), but the session disposed and a new one issued, which met my requirements -
WTFZane about 7 yearsBut what if I use
Session.Abandon
to just clear a specific shopping basket?