In this article I will explain with an example, how to enable Session in ASP.Net Core (.Net Core 2).
Note: For beginners in ASP.Net Core (.Net Core 2), please refer my article ASP.Net MVC Core 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 UseMvc method.
 
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   //Enable Session.
    app.UseSession();
 
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{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 2: Set custom Session Timeout in ASP.Net Core.
 
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
 
    services.AddSession();
}
 
.Net Core 2: Enable Session in ASP.Net Core
 
Note: For more details on using Session in ASP.Net Core (.Net Core 2), please refer my article .Net Core 2: Using Session in ASP.Net Core.
 
 

Downloads



Other available versions