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

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)

This question is related to c# asp.net session razor webmatrix

The answer is


It is also a good idea to instruct the client browser to clear session id cookie value.

Session.Clear();
Session.Abandon();
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-10);

From what I tested:

Session.Abandon(); // Does nothing
Session.Clear();   // Removes the data contained in the session

Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"

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.


Session.Abandon()

This marks the session as Abandoned, but the session won't actually be Abandoned at that moment, the request has to complete first.


Session.Abandon()

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.


Session["YourItem"] = "";

Works great in .net razor web pages.


Session.Abandon() this will destroy the data.

Note, this won't necessarily truly remove the session token from a user, and that same session token at a later point might get picked up and created as a new session with the same id because it's deemed to be fair game to be used.


You kill a session like this:

Session.Abandon()

If, however, you just want to empty the session, use:

Session.Clear()

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

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.

HttpContext.Current.Session.Abandon();

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC

Examples related to webmatrix

How to Kill A Session or Session ID (ASP.NET/C#) How do I import a namespace in Razor View Page?