在 .NET 8.0 中,如果你遇到了 System.InvalidOperationException 异常,提示"Session has not been configured",这通常意味着你的应用程序试图使用会话(Session)功能,但是会话状态管理没有被正确配置。在 ASP.NET Core 中,会话是通过中间件来配置的,而不是在全局的 web.config 文件中设置。
要解决这个问题,你可以按照以下步骤进行:
1. 添加 Session 中间件
确保你的应用程序中添加了 Session 中间件。你可以在 Startup.cs 或 Program.cs 文件中配置它。
在 Program.cs 中配置(适用于 ASP.NET Core 5.x 及以后版本)
服务注册:
// 添加 Session 服务
builder.Services.AddSession();
启动配置:
app.UseSession(); // 使用 Session 中间件
cs
var builder = WebApplication.CreateBuilder(args);
// 添加 Session 服务
builder.Services.AddSession();
var app = builder.Build();
// 确保在 app.UseRouting() 和 app.UseAuthentication() 之后调用
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession(); // 使用 Session 中间件
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();


2. 配置 Session 存储提供程序
默认情况下,ASP.NET Core 使用内存中的会话存储。如果你需要持久化会话(例如,在多个实例之间共享会话),你可以使用其他存储提供程序,如 SQL Server、Redis 等。例如,使用 Redis:
cs
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10); // 设置空闲超时时间
options.Cookie.HttpOnly = true; // 设置 cookie 为 HttpOnly
});
然后,你可以使用 StackExchange.Redis 来存储会话数据:
cs
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost"; // Redis 服务器地址和端口号
});
更多: