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

前端 未结 9 1270
礼貌的吻别
礼貌的吻别 2020-11-30 04:09

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 t

相关标签:
9条回答
  • 2020-11-30 04:22

    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.

    0 讨论(0)
  • 2020-11-30 04:30

    You kill a session like this:

    Session.Abandon()
    

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

    Session.Clear()
    
    0 讨论(0)
  • 2020-11-30 04:31
    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.

    0 讨论(0)
  • 2020-11-30 04:34

    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.

    0 讨论(0)
  • 2020-11-30 04:36

    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();
    
    0 讨论(0)
  • 2020-11-30 04:37

    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);
    
    0 讨论(0)
提交回复
热议问题