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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Jack
  • 9,843
  • 23
  • 78
  • 111

10 Answers10

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

Ryan Cook
  • 9,275
  • 5
  • 38
  • 37
  • 10
    I try Session.Abandon but it still not clearing out the session. – Jack Dec 05 '08 at 23:14
  • 1
    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. – Ryan Cook Dec 06 '08 at 02:20
35

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", ""));
kat1330
  • 5,134
  • 7
  • 38
  • 61
  • 3
    +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. – Matt Jul 14 '15 at 10:28
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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
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.

BrainCoder
  • 5,197
  • 5
  • 30
  • 33
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

Padhraic
  • 5,112
  • 4
  • 30
  • 39
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().

Amey P Naik
  • 710
  • 1
  • 8
  • 18
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>  
David McLean
  • 1,462
  • 1
  • 12
  • 27
Lucky
  • 19
  • 1
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;
        }
    }
0

Session.Clear();

BobbyShaftoe
  • 28,337
  • 7
  • 52
  • 74
-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

Community
  • 1
  • 1
Darshan
  • 71
  • 3
  • 3
    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. – Oskar Berggren Apr 25 '16 at 02:16
  • Not for session, just for Cache. – MorgoZ Sep 26 '19 at 13:18