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 7) MVC.
Note: This solution is strictly applicable to ASP.Net Core application using .Net Core version 7 framework.
Error
This error occurs when Session state is used in ASP.Net Core (.Net Core 7) application without configuring Session.
Solution
The solution to this problem is to enable the Session in ASP.Net Core application.
Inside the Program.cs class, Session is enabled using the UseSession method of the app object.
Note: It is mandatory to call the UseSession method before the Run method.
Then, you need to call the AddSession method of the Services property of builder object.
var builder = WebApplication.CreateBuilder(args);
//Enabling MVC
builder.Services.AddControllersWithViews();
builder.Services.AddHttpContextAccessor();
//Set Session Timeout. Default is 20 minutes.
builder.Services.AddSession((options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(45);
});
var app = builder.Build();
app.UseSession();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Downloads