In this article I will explain with an example, how to solve the following error: Session has not been configured for this application or request in ASP.Net Core (.Net Core 5) MVC.
Note: This solution is strictly applicable to ASP.Net Core application using .Net Core version 5 framework.
Error
This error occurs when Session is used in ASP.Net Core (.Net Core 5) application without configuring Session.
Solution
The solution to this problem is to configure and enable the Session in ASP.Net Core application.
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.
The AddSession can be called directly without any parameters and it can also be used to set the IdleTimeout property which sets the Session Timeout duration.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//Set Session Timeout. Default is 20 minutes.
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
}
Downloads