Search code examples
c#asp.nethttpcontextsessionid

ASP.NET sessionID will not update


I click on refresh button which should restart session:

protected void btnRefresh_Click(object sender, EventArgs e)
{

    HttpContext.Current.Session.Abandon();
    HttpCookie mycookie = new HttpCookie("ASP.NET_SessionId");
    mycookie.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Add(mycookie);
    LblSessionID.Text = HttpContext.Current.Session.SessionID+
        " test btnRefresh_Click";
    LblIsNewSession.Text = Session.IsNewSession.ToString();
}

But when the button is clicked, the SessionID value in LblSessionID still displays the old value but another label LblIsNewSession will show it as true for IsNewSession. The LblSessionID will then reflect the actual SessionID value when I use asp.net control (like dropdown) that has autopostback="true" and from there SessionID sticks around.

I do use global.asax

Any idea why LblSessionID isn't behaving as it should and is waiting for next postback to start reflecting actual value?

When I launch the web application, the problem is the same - LblSessionID show different value and then change after first postback and stays the same from there.


Solution

  • That's the way it works - If you Abandon the session it won't reflect that until the next Request. It makes sense if you think about it...

    Say you have a user that accesses your site and gets a Session ID of 123 (not reflective of an actual value, I know). When you click your button to get a new Session ID, the user's request is from the old Session, and that is the value that is reflected during that Request. Once the session is reset (or abandoned or whatever), the user gets a new Session ID of 321 and subsequent Request's will then reflect that new session ID.