'ASP.NET Core Session Timeout

I remember we have used session.timeout in ASP.NET to change the session timeout which was 20 minutes if not changed.

I tried to change the session time out in ASP.NET Core 3.1 in Startup.cs but nothing happens. I use Identity for operators and set the Idle Timeout for 5 hours 'I Think' but operators sign out after 1-2 minutes and should re-login hundreds of times for completing an article.

services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(5);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

What am I missing ??



Solution 1:[1]

For using session state in an ASP.NET Core you need to add the session middleware to your pipeline.

important: The order of middleware is the key. Call UseSession between UseRouting and UseEndpoints.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();
}

More info : MSDN

Solution 2:[2]

As you said you are using identity then use the following code in your startup.cs class after services.AddIdentity().

public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddAuthentication().AddCookie(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromHours(5);
        });
    }

Solution 3:[3]

public void ConfigureServices(IServiceCollection services)
{
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });
}

The preceding code sets a short timeout to simplify testing.

The order of middleware is important. Call UseSession after UseRouting and before UseEndpoints. See Middleware Ordering.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSession();
}

HttpContext.Session is available after session state is configured.

HttpContext.Session can't be accessed before UseSession has been called.

A new session with a new session cookie can't be created after the app has begun writing to the response stream. The exception is recorded in the web server log and not displayed in the browser.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 XAMT
Solution 2 Zubair Rana
Solution 3 dbc