How to Kill A Session or Session ID (ASP.NET/C#)

anon271334 picture anon271334 · Mar 16, 2011 · Viewed 169.5k times · Source

How can I destroy a session (Session["Name"]) when the user clicks the logout button?

I'm looking through the ASP.NET API Reference on MSDN and it doesn't seem to have much information. It seems rather limited. But I cannot find any other pages for ASP.NET Classes etc.

I have tried:

Session.Abandon(); and Session.Contents.Remove("Name"); neither of them work. ( I found these in a forum from a Google search)

Answer

Kelsey picture Kelsey · Mar 16, 2011

The Abandon method should work (MSDN):

Session.Abandon();

If you want to remove a specific item from the session use (MSDN):

Session.Remove("YourItem");

EDIT: If you just want to clear a value you can do:

Session["YourItem"] = null;

If you want to clear all keys do:

Session.Clear();

If none of these are working for you then something fishy is going on. I would check to see where you are assigning the value and verify that it is not getting reassigned after you clear the value.

Simple check do:

Session["YourKey"] = "Test";  // creates the key
Session.Remove("YourKey");    // removes the key
bool gone = (Session["YourKey"] == null);   // tests that the remove worked