Unique Session Id on Each Browser Tab






4.64/5 (4 votes)
Manage Unique page id for sessions on each browser tab
Introduction
When we create session in ASP.NET web application, then these sessions merge to each other on each tab. This is the solution how can we make each session unique.
Using the Code
To manage session id, we create a "UniquePageIdControl
".
- Create a web user control "
UniquePageIdControl
":using System; using System.Web.UI; public partial class UserControl_UniquePageIdControl : UserControl { private string _pageUniqueId = Guid.NewGuid().ToString(); public string PageUniqueId { get { return _pageUniqueId; } } protected override object SaveControlState() { //Use an object array to store multiple values. //This can be expanded to store business objects instead //of just one value such as CustomerID. var controlState = new object[2]; controlState[0] = base.SaveControlState(); controlState[1] = _pageUniqueId; return controlState; } protected override void LoadControlState(object savedState) { var controlState = (object[]) savedState; base.LoadControlState(controlState[0]); _pageUniqueId = (string) (controlState[1]); } protected override void OnInit(EventArgs e) { base.OnInit(e); Page.RegisterRequiresControlState(this); } }
- Create a Page base class to create Session Name:
using System.Web.UI; /// <summary> /// Summary description for PageBase /// </summary> public class PageBase : Page { protected string CreateSession(string pageUniqueId, SessionNames sessionName) { return string.Format("{0}-{1}", pageUniqueId, sessionName); } }
- Inherit
PageBase
class to aspx page and callCreateSession
method:using System; using System.Collections.Generic; public partial class _Default : PageBase { protected void Page_Load(object sender, EventArgs e) { var sessionName = CreateSession(UniquePageIdControl.PageUniqueId, SessionNames.TestingSession); Session[sessionName] = new List<string>(); Response.Write(sessionName); } } public enum SessionNames { TestingSession }
Default.aspx page is as follows:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/UserControl/UniquePageIdControl.ascx"
TagPrefix="uc1" TagName="UniquePageIdControl" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:UniquePageIdControl runat="server" ID="UniquePageIdControl" />
</div>
</form>
</body>
</html>
Points of Interest
And open page in different pages each session will have a new name.