How to clear out session on log out
Asked Answered
T

10

65

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?

Thibaud answered 5/12, 2008 at 21:12 Comment(0)
S
71
Session.Abandon()

http://msdn.microsoft.com/en-us/library/ms524310.aspx

Here is a little more detail on the HttpSessionState object:

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate_members.aspx

Springspringboard answered 5/12, 2008 at 21:15 Comment(2)
I try Session.Abandon but it still not clearing out the session.Thibaud
Something strange is happening, because Session.Abandon() should give the user a new session. Maybe you have a different problem, if you find more/better data: post it and I'm sure the community will try to help out.Springspringboard
U
36

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", ""));
Unteach answered 14/11, 2014 at 18:13 Comment(1)
+1 for this: Very good answer, it is the only clean way to do it. WIthout setting ASP.NET_SessionId to empty string the old session ID would still be used (which can be verified with developer toolbar F12, Network, Details). I've tried it before with only .Clear and .Abandon, but this 3rd step is really needed.Cyan
C
21

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.

Casaubon answered 5/12, 2008 at 21:18 Comment(0)
R
14

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.

Rustcolored answered 18/8, 2012 at 9:36 Comment(1)
I think this is the best answer so far.Kishke
H
3

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

Howrah answered 19/1, 2018 at 5:29 Comment(0)
C
1
<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>  
Consociate answered 25/5, 2011 at 12:33 Comment(0)
T
1

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().

Trisa answered 13/4, 2018 at 7:8 Comment(0)
B
1

for .Net core

[HttpPost]
    public IActionResult Logout()
    {
        try
        {
            CookieOptions option = new CookieOptions();
            if (Request.Cookies[AllSessionKeys.AuthenticationToken] != null)
            {
                option.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Append(AllSessionKeys.AuthenticationToken, "", option);
            }

            HttpContext.Session.Clear();
            return RedirectToAction("Login", "Portal");
        }
        catch (Exception)
        {
            throw;
        }
    }
Body answered 7/7, 2022 at 13:17 Comment(0)
S
0

Session.Clear();

Serle answered 5/12, 2008 at 21:14 Comment(1)
Session.Abandon() removes session and events. .Clear doesn't get everything.Condemn
M
-1

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

Mosira answered 6/1, 2016 at 6:0 Comment(2)
Just to clarify, note that this code DOES NOT clear any session data - it only discourages the user's web browser from caching data, and could have implications for performance if applied carelessly.Cowes
Not for session, just for Cache.Orit

© 2022 - 2024 — McMap. All rights reserved.