asp.net - session - multiple browser tabs - different sessions?

71,211

Solution 1

To facilitate multi-tab session states for one user without cluttering up the URL, do the following.

In your form load function, include:

If Not IsPostback Then
  'Generate a new PageiD'
  ViewState("_PageID") = (New Random()).Next().ToString()
End If

When you save something to your Session State, include the PageID:

Session(ViewState("_PageID").ToString() & "CheckBoxes") = D

Notes:

  • As with session ID's in general, you cannot trust that malicious viewers will not change the SessionID / PageID. This is only a valid solution for an environment where all users can be trusted. Fortunately, ViewState does offer more protection than using a hidden input field.
  • You will not have access to the PageID until the ViewState is restored upon PostBack. Therefore, you will not have access to the PageID in the page_init() handler.

Solution 2

<configuration>
  <system.web>
    <sessionState cookieless="true"
      regenerateExpiredSessionId="true" />
  </system.web>
</configuration>

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

in this case each tab will get unique ID and it will looks like it is another visitor.

Solution 3

Using Brian Webster's answer I found a problem with XMLHttpRequests. It turned out, XMLHttpRequests did not set the IsPostback flag to true and therefore the request looked like a new request and one would end up having a new session state for that request. To solve that problem I also checked the value of the ViewState("_PageID")

so that my code looks like this in C#:

protected dynamic sessionVar; //a copy of the session variable

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack && ViewState["_PageID"] == null)
    {
        ViewState["_PageID"] = (new Random()).Next().ToString();
        Session[ViewState["_PageID"] + "sessionVar"] = initSessionVar(); //this function should initialize the session variable
    }
    sessionVar = Session[ViewState["_PageID"] + "sessionVar"];
    //...
}
Share:
71,211
Brian Webster
Author by

Brian Webster

[email protected]

Updated on February 20, 2020

Comments

  • Brian Webster
    Brian Webster about 4 years

    I'd like to maintain a session state per browser tab.

    Is this easy (or even possible) to do in ASP.NET?

    Example: A user hits Ctrl-T in firefox 5 times and visits the site in each tab. I'd like each tab to have its own session state on the server