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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.
Method 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.
Method 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"]; //... }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0