1

I am trying to set the session timeout to 30 mins in .NET 6. I added the following code for it.

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
options.IdleTimeout = TimeSpan.FromMinutes(30));

It is not working and the session is expiring in a few minutes.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132

1 Answers1

0

When session is expired, the server will delete all session variables set on login and there is no way to see if it has been expired from client side (one of the many reasons on why I switched from Sessions to JsonWebTokens).

To use session, add following code in your Program.cs

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;

    // make the session cookie Essential
    // so that session variable is not null
    // check this StackOverflow answer: https://stackoverflow.com/a/64984796/19112855
    options.Cookie.IsEssential = true;
});

app.UseSession(); // before app.UseAuthentication(); and after app.UseRouting();

To manually delete all session variables, call this in your controller HttpContext.Session.Clear();

Codingwiz
  • 192
  • 2
  • 14
  • Codingwiz, worked locally but not on the server. I find that server has its own configurations. It might be the issue as it is working fine in local IIS. – Thomas Charles Feb 03 '23 at 14:31