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

asp.net.NetSessionSession State

asp.net Problem Overview


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?

asp.net Solutions


Solution 1 - asp.net

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 - asp.net

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 - asp.net

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.

Solution 4 - asp.net

I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.

public static void RemoveEverythingButUserInfo()
{
    foreach (String o in HttpContext.Current.Session.Keys)
    {
        if (o != "UserInfoIDontWantToAskForAgain")
            keys.Add(o);
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLance FisherView Question on Stackoverflow
Solution 1 - asp.netsplattneView Answer on Stackoverflow
Solution 2 - asp.netshabbirhView Answer on Stackoverflow
Solution 3 - asp.netKasim ShafiqView Answer on Stackoverflow
Solution 4 - asp.netMatthewMartinView Answer on Stackoverflow