[asp.net] How to clear out session on log out

I redirect the user to the login page when user click log out however I don't think it clears any application or session because all the data persisted when the user logs back in.

Currently the login page has a login control and the code behind on the page is only wired up the login Authenticate.

Can someone direct me to a good tutorial or article about handling log in and out of ASP.NET web sites?

This question is related to asp.net .net asp.net-session

The answer is


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 him to relogin for example) and reset all his session specific data.


Session.Clear();


The way of clearing the session is a little different for .NET core. There is no Abandon() function.

ASP.NET Core 1.0 or later

//Removes all entries from the current session, if any. The session cookie is not removed.
HttpContext.Session.Clear()

See api Reference here

.NET Framework 4.5 or later

//Removes all keys and values from the session-state collection.
HttpContext.Current.Session.Clear(); 

//Cancels the current session.
HttpContext.Current.Session.Abandon();

See api Reference here


Session.Clear();


Go to file Global.asax.cs in your project and add the following code.

    protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.Now.AddHours(-1));
        Response.Cache.SetNoStore();
    }

It worked for me..! Reference link Clear session on Logout MVC 4


I would prefer Session.Abandon()

Session.Clear() will not cause End to fire and further requests from the client will not raise the Session Start event.


I use following to clear session and clear aspnet_sessionID:

HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

session.abandon() will not remove the sessionID cookie from the browser. Therefore any new requests after this will take the same session ID. Hence, use Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); after session.abandon().


I would prefer Session.Abandon()

Session.Clear() will not cause End to fire and further requests from the client will not raise the Session Start event.


Go to file Global.asax.cs in your project and add the following code.

    protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.Now.AddHours(-1));
        Response.Cache.SetNoStore();
    }

It worked for me..! Reference link Clear session on Logout MVC 4


session.abandon() will not remove the sessionID cookie from the browser. Therefore any new requests after this will take the same session ID. Hence, use Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); after session.abandon().


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 him to relogin for example) and reset all his session specific data.


<script runat="server">  
    protected void Page_Load(object sender, System.EventArgs e) {  
        Session["FavoriteSoftware"] = "Adobe ColdFusion";  
        Label1.Text = "Session read...<br />";  
        Label1.Text += "Favorite Software : " + Session["FavoriteSoftware"];  
        Label1.Text += "<br />SessionID : " + Session.SessionID;  
        Label1.Text += "<br> Now clear the current session data.";  
        Session.Clear();  
        Label1.Text += "<br /><br />SessionID : " + Session.SessionID;  
        Label1.Text += "<br />Favorite Software[after clear]: " + Session["FavoriteSoftware"];  
    }  
</script>  



<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>asp.net session Clear example: how to clear the current session data (remove all the session items)</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:Teal">asp.net session example: Session Clear</h2>  
        <asp:Label   
            ID="Label1"   
            runat="server"   
            Font-Size="Large"  
            ForeColor="DarkMagenta"  
            >  
        </asp:Label>  
    </div>  
    </form>  
</body>  
</html>  

Session.Clear();


The way of clearing the session is a little different for .NET core. There is no Abandon() function.

ASP.NET Core 1.0 or later

//Removes all entries from the current session, if any. The session cookie is not removed.
HttpContext.Session.Clear()

See api Reference here

.NET Framework 4.5 or later

//Removes all keys and values from the session-state collection.
HttpContext.Current.Session.Clear(); 

//Cancels the current session.
HttpContext.Current.Session.Abandon();

See api Reference here


I would prefer Session.Abandon()

Session.Clear() will not cause End to fire and further requests from the client will not raise the Session Start event.


I use following to clear session and clear aspnet_sessionID:

HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

I would prefer Session.Abandon()

Session.Clear() will not cause End to fire and further requests from the client will not raise the Session Start event.


<script runat="server">  
    protected void Page_Load(object sender, System.EventArgs e) {  
        Session["FavoriteSoftware"] = "Adobe ColdFusion";  
        Label1.Text = "Session read...<br />";  
        Label1.Text += "Favorite Software : " + Session["FavoriteSoftware"];  
        Label1.Text += "<br />SessionID : " + Session.SessionID;  
        Label1.Text += "<br> Now clear the current session data.";  
        Session.Clear();  
        Label1.Text += "<br /><br />SessionID : " + Session.SessionID;  
        Label1.Text += "<br />Favorite Software[after clear]: " + Session["FavoriteSoftware"];  
    }  
</script>  



<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>asp.net session Clear example: how to clear the current session data (remove all the session items)</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:Teal">asp.net session example: Session Clear</h2>  
        <asp:Label   
            ID="Label1"   
            runat="server"   
            Font-Size="Large"  
            ForeColor="DarkMagenta"  
            >  
        </asp:Label>  
    </div>  
    </form>  
</body>  
</html>  

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

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net-session

What is the difference between Session.Abandon() and Session.Clear() How can I set the Secure flag on an ASP.NET Session Cookie? How to clear out session on log out