Search code examples
c#asp.net-mvcmvvmsession-variablesasp.net-mvc-viewmodel

Session Variable Lost after return Redirect function


I have an mvvm web app that is used for sorting values The user clicks on sort and the following code within the element sends it to controller as a parameter, refreshing the page.

<a href="@Url.Action("Sort", new { area = "Area", controller = "Controller", sorter = ViewModelListSorterValue.CREATEDATE_ASC })">

this is the function that works in the controller in return.

Public ActionResult Sort(ViewModelListSorterValue sorter)
        {
            ViewModelListSort sortViewModel = new ViewModelListSort();
            sortViewModel.Value = sorter;
            HttpContext.Session["key"] = sortViewModel;

            return RedirectToAction("List");
        }

The code is supposed to load the sorter's value by getting it from session in each page with another function in the same controller, which is also invoked with an href tag and the following line.

sortViewModel= HttpContext.Session["key"] as ViewModelListSort;

The first page loads fine, however when I change it to the second page, the Session's variable turns up null and the sort turns to default

The code works fine for first few pages in firefox but I had no luck in microsoft edge, explorer and google chrome.

I have tried return RedirectToAction("List", false); as well but to no avail. What am I doing wrong?


Solution

  • It's a problem of setting multiple worker processes in your IIS application pool.

    Multiple processes are processes that run in isolation from each other which causes problems of session state sharing by default. We can configure to store session state out of process so it can be shared, but that is another story.

    Regarding how many worker processes, this is a tradeoff and should be adjusted based on each application.

    In general, the main benefit of running as multiple worker processes is for fault isolation, so if one process goes down, the application is still able to run. It's also a quick solution to blocking code so that you can still achieve a higher level of concurrency in your application at the cost of decreasing performance due to more context switching between processes/threads.