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)
It is also a good idea to instruct the client browser to clear session id cookie value.
is what you should use. the thing is behind the scenes asp.net will destroy the session but immediately give the user a brand new session on the next page request. So if you're checking to see if the session is gone right after calling abandon it will look like it didn't work.
From what I tested:
Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)
In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.
So, to conclude this: Use Session.Clear() and save frustration.
Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.
The
Abandon
method should work (MSDN):If you want to remove a specific item from the session use (MSDN):
EDIT: If you just want to clear a value you can do:
If you want to clear all keys do:
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.Abandon();
did not work for me either.The way I had to write it to get it to work was like this. Might work for you too.
Works great in .net razor web pages.