Unique session in multiple browser tabs in ASP.NET MVC

后端 未结 3 1539
遥遥无期
遥遥无期 2020-12-16 03:54

I want to create unique session whenever user open a new browser tab or window in ASP.NET MVC application. Is it possible in ASP.NET / MVC ?

I tried to follow below

3条回答
  •  遥遥无期
    2020-12-16 04:33

    As you know, HTTP is stateless and a very common mechanism to have state between requests is use session variables. The problem occurs when you open a new brower tab because the session is the same so any change you make in the new tab is gonna impact other tabs. You didn't specify exactly what you want to do but let's say that you have a product list page where the user can enter search filters and you want to save them in the session. If the user sets a search filter value in tab 1, tab 2 is gonna have the same value (they share session variables). What you can do?

    1) Use this approach for adding a guid in the URL: http://www.codeproject.com/Articles/331609/Get-an-unique-session-in-each-browser-tab

    2) Do something similar to what's described in the previous point but not in the same way and this is what I did to solve the same problem.

    a) My links to the serach page are /Product/List?guid=xxx instead of just /Product/List. If the user manually types /Product/List, I'm redirecting him to a new URL where the GUID is set.

    public ActionResult List(string guid)
            {
                if (guid == null)
                {
                    return RedirectToAction("List", new { guid = Guid.NewGuid().ToString() });
                }
    ...
    

    Every time you click on the "list" link and target a new tab, a new GUID is generated.

    b) I have a session key with the GUID so each page has its own values. You can have 2 tabs opened at the same time and they are gonna be using different session values because the guid is gonna be different.

    This solution is not perfect but at least it works.

    I hope it helps.

提交回复
热议问题