Darcy Q
Darcy Q

Reputation: 55

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.

Upvotes: 3

Views: 3500

Answers (4)

Starbuck3000
Starbuck3000

Reputation: 79

It is not your code, it is a documented behavior: "The Abandon method sets a flag in the session state object that indicates that the session state should be abandoned. The flag is examined at the end of the page request. Therefore, the user can still use session objects after you call the Abandon method. As soon as the page processing is completed, the session is removed." (source: http://support.microsoft.com/kb/899918)

The Abandon() method flags the session collection for clearing at the end of the request, it does not actually clear it immediately.

You can either call the RemoveAll() or Clear() methods for instant deletion of the objects, or issue a Response.Redirect call to the page itself and re-test for the existence of the data.

Upvotes: 0

Dave Zych
Dave Zych

Reputation: 21887

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.

Upvotes: 2

Garry
Garry

Reputation: 5074

try

   Session.RemoveAll();

    Session.Clear(); 

Upvotes: 0

spender
spender

Reputation: 120498

SessionId is not reliable unless you actually store something (anything) in the session.

Upvotes: 0

Related Questions