In this article I will explain with an example, how to enable Session in ASP.Net Core (.Net Core 5).
Note: For beginners in ASP.Net Core (.Net Core 5), please refer my article ASP.Net Core 5: Hello World Tutorial with Sample Program example.
 
 

Enabling Session

Inside the Startup.cs class, Session is enabled using the UseSession method of the app object inside the Configure method.
Note: It is mandatory to call the UseSession method before the UseEndpoints method.
 
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //Enable Session.
    app.UseSession();
 
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
 
Then, inside the ConfigureServices method, you need to call the AddSession method of the services object.
Note:The default Session Timeout in ASP.Net Core is 20 minutes. If you want to set custom Session timeout, please refer my article .Net Core 5: Set custom Session Timeout in ASP.Net Core.
 
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
 
    services.AddSession();
}
 
.Net Core 5: Enable Session in ASP.Net Core
 
Note: For more details on using Session in ASP.Net Core (.Net Core 5), please refer my article .Net Core 5: Using Session in ASP.Net Core.
 
 

Downloads



Other available versions