Search code examples
asp.net-core.net-coreasp.net-core-7.0

Setting lifespan of session in .NET 7.0 webapp


I am rather new to .NET and I am trying to leave a session cookie in the browser and set its timespan.

This is my Program.cs, more or less taken from tutorials and StackOverflow answers I found:

using MyApp.Utils;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddRazorPages();

// Is executed after app.UseSession ();
builder.Services.AddSession(options => 
{
    // Set session timeout
    options.IdleTimeout = TimeSpan.FromMinutes(30); 
    options.Cookie.HttpOnly = true;

    // Make the session cookie essential
    options.Cookie.IsEssential = true; 
    options.Cookie.MaxAge = TimeSpan.FromDays(365);    
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

// Is executed before builder.Services.AddSession (options... ) 
app.UseSession(); 

app.UseAuthorization();

app.MapRazorPages();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

EnvironmentSettings.GetSettings(); // Gets settings from INI file.

app.UseHttpsRedirection();
app.UseAuthentication();

app.MapControllers();
app.UseDefaultFiles();
app.MapRazorPages();

app.Run();

This is all I see in the browser:

enter image description here

Can anyone see what I am doing wrong?

If it helps, I noticed that app.UseSession is executed before builder.Services.AddSession(options => ... )


Solution

  • What you have looks normal and yes, it is expected that the delegate that is passed to AddSession doesn't get run straight away. It likely gets run when a new session is created.

    Speaking of which, a new session doesn't get created until something is added in to the session which needs to be recalled. Until then a session cookie won't be created either, there's no point adding the overhead unless it's needed.