Search code examples
c#asp.netsessionviewdatatempdata

How do I save data in MVC's Session when the load balancer isn't "sticky"?


I need to save information in the session and make it available to all web servers in the farm, as the HTTP sessions aren't sticky.

I believe this means that I need to use a shared-in memory session state provider.

That being said, how do I actually put data into that store from code?

TempData, ViewBag, and all the other variants seem to only work on one page, and I need some variables accessible in multiple pages.


Solution

  • There are different session state providers, including a SQL Server session state provider. You configure it in your web.config

    http://support.microsoft.com/kb/317604

    and then use the Session container normally.

    To add:

    HttpContext.Current.Session.Add( key, val );
    

    To retrieve:

    object val = HttpContext.Current.Session["key"]