1

I am facing session expire issue when load balancer switches the server of my application.

I want to share session in between 2 servers through Load balancer in Asp.net Core can any one suggest me how to implement inproc session?

Thanks.

Anil Kumar
  • 23
  • 6
  • 2
    Use redis or SQL – davidfowl Sep 12 '18 at 07:13
  • Davids answer is the most straightforward and correct one and works always. If for some reason you can't do it, a common practice used in the past was "session pinning" on the load balancer itself. A user who gets redirected to one server will always be routed there by the load balancer, so it may cause an somewhat uneven distribution and can result one of the instances having higher load than others – Tseng Sep 12 '18 at 07:24

1 Answers1

3

InProc session will not help you, since it resides only on the web server. If you switch servers due to loadbalancing or fail over, you lose the session. What you are looking for is an IDistributedCache. Examples using Redis or SQL can be found in the docs (Seriously, read them. They are awesome!)

If you want to use Redis you need to install the package for it first

Install-Package Microsoft.Extensions.Caching.Redis

After that, configure it on your ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedRedisCache(options =>
    {
        options.Configuration = "localhost";
        options.InstanceName = "SampleInstance";
    });
}

Then add the .UseSession to your Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    /*... omitted ...*/
    app.UseCookiePolicy();
    app.UseSession();
    app.UseHttpContextItemsMiddleware();
    app.UseMvc();
}

}

Marco
  • 22,856
  • 9
  • 75
  • 124
  • I need to implement something similar. I used sessions but as we want to configure load balancer, need to replace sessions with something else. Can I use DistributedCache to manage LoggedIn User's details? If we want to use DistributedCache, we need to pass key to access the values from cache. How to keep a key(i.e. UserId) across multiple requests? – Priya May 15 '20 at 07:33
  • You can store user information in a token, cookie, distributed cache. There is loads of possibilities. It would be best suited to describe your problem in a seperate question. – Marco May 15 '20 at 08:43
  • Thank you. I've added a question here : https://stackoverflow.com/questions/61813486/alternatives-of-inproc-sessions-in-net-core If you can suggest a suitable solution? – Priya May 15 '20 at 09:13