.Net 6 - Different session for each browser tab – diff images in each

Andrew Harkins 46 Reputation points
2022-05-23T21:52:29.033+00:00

I been having some major issues with this, I feel like this shouldn’t be so hard but.. I am trying to be able to open a link which brings pictures to the browser to display them. I have this working. What I am trying to do is when someone opens another link itll open a new tab and they will have those new pictures in that tab and the previous pictures in the other tab. I tried to do this with Sessions but it overwrites the session, and both tabs show the same pics. I now coded it up so I have a different session guid for each tab and I go to try to view the pics but the same thing happens. The tab is over written. My new idea is to save this huge text file in a hidden variable on the page and read from that. But when I do this my tempdata var says the page cannot be found but if I remove the tempdata var the page works… I rewrote a bunch of methods some multiple times. Any ways to make this work would be greatly appreciated

public async Task<ActionResult> PopulateFileCache(string folderPath)
        {
            if (!string.IsNullOrEmpty(folderPath))
            {                
                using var client = _httpClient.CreateClient("MesserAPI");
                try
                {
                    using var response = await client.GetAsync($"/api/File/GetFolderFiles?folderPath={folderPath}");
                    if (response.IsSuccessStatusCode)
                    {
                        var lstFiles = await response.Content.ReadAsStringAsync();
                        ViewData["lstParts"] = lstFiles;

                        TempData["SlideTotal"] = 0;

                        if (_contextAccessor.HttpContext.Session.IsAvailable)
                        {
                            SaveToSession(lstFiles);
                        }
                        TempData["guid"] = _contextAccessor.HttpContext.Session.GetString("sGUID") ?? string.Empty;
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
            return RedirectToAction("FileViewer");
        }


public IActionResult ReturnData(string sessionID)
        {
            //if (objFiles != null)
            //{
                if (TempData != null)
                {
                    TempData.Keep();
                }
                List<LNPartVM> lNParts = null;
                try
                {
                    //var jsonResponse = objFiles;
                    //var jsonResponse = GetFromSession();
                    var jsonResponse = GetFromSession(sessionID);
                    if (!string.IsNullOrWhiteSpace(jsonResponse))
                    {
                        lNParts = JsonSerializer.Deserialize<List<LNPartVM>>(jsonResponse);
                    }

                    if (lNParts?.Count > 0)
                    {
                        TempData["SlideTotal"] = lNParts.Count;
                        _contextAccessor.HttpContext.Session.SetInt32("SlideTotal", lNParts.Count);
                        int partIndex = 0;

                        try
                        {
                            partIndex = (int)(_contextAccessor.HttpContext.Session.GetInt32("PartIndex") == null ? 0 : _contextAccessor.HttpContext.Session.GetInt32("PartIndex"));
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.Message);
                        }
                        LNPartVM partVM = lNParts[partIndex];
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            //}
            return ViewComponent("DataPage");
        }
        public string GetSessionID()
        {
            return _contextAccessor.HttpContext.Session.Id;
        }
        public string GetSessionGUID()
        {
            return Guid.NewGuid().ToString();
        }
        //string sessionName,
        public IActionResult SaveToSession(string obj)
        {
            bool status = false;
            // Same Session across browsers
            //string sessionID = GetSessionID();
            string sessionID = GetSessionGUID();

            if (!string.IsNullOrWhiteSpace(sessionID))
            {
                _contextAccessor.HttpContext.Session.SetString(sessionID, obj);
                _contextAccessor.HttpContext.Session.SetString("sGUID", sessionID);
                status = true;
            }
            else
            {
                _contextAccessor.HttpContext.Session.SetString("SessionPN", obj);
                status |= true;
            }

            if (status)
            {
                return Content("Session Saved");
            }
            return Content("Session Error");
        }

  public async Task<IActionResult> FileViewer()
        {
            return View();
        }
This is on the HTML page

$('#btnNext').click(function (e) {
    e.preventDefault();

    console.log(iSlideCount);

    if (iSlideCount > 0) {
        $.ajax({
            type: 'GET',
            url: '@Url.Action("NextPart", "File")',
            contentType: 'Json'
        })
        .done(function(e) {
            var sguid = $("#txthguid").val();
            var route = '@Url.Action("ReturnData","File", new { sessionID="-1" })';
            route = route.replace("-1", sguid);
            $('#contentData').load(route);

            //$('#contentData').load('@Url.Action("ReturnData","File")');

            //$('#part').load('@Url.Action("ReturnData","File")');
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,926 Reputation points Volunteer Moderator
    2022-05-24T15:10:02.013+00:00

    the typical work around for this is to use cookie-less session ids. that I the session is in the url. you then control on a link whether it is the current or a new session.

    0 comments No comments

  2. Andrew Harkins 46 Reputation points
    2022-05-24T19:33:04.63+00:00

    The use-case for this project is so users can open a folder of files and view them in the browser, then they can open another folder and view those files in the browser. If the user wanted to see the first folder of files they could switch tabs and view the files they first opened.
    Currently my project when the users open a new tab it overwrites all the old files in the tab with the new tabs files.

    @ari
    Yes all my files are in Base64. I read all the files into memory and put them into a list. Then I read the file encoded bytes and decode it back to the browser.

      if (lNParts[partIndex].FileName.EndsWith(".pdf"))  
                                {  
                                    _logger.LogInformation("File is a PDF");  
                                    var base64 = Convert.ToBase64String(lNParts[partIndex].FileBytes);  
                                    imgSrc = string.Format("data:application/pdf;base64,{0}", base64);  
        }  
    

    1 thing that i was able to do is when I have multiple tabs each tab has its own Session GUID. So my session has [tab1][tab2][etc] but when try to read the specific tab name it overwrites all the tabs. I even tried saving the specific session name in a hidden variable on the html page and reading it in.
    still no luck successfully.

    I will look into cookieless session ids and do some research on them.

    Thank you everyone

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.