ASP.NET新手遭遇Session未配置异常,请求原因分析
System.InvalidOperationException with Session? Hey there, since you're new to ASP.NET, let's break down exactly why you're seeing this error and how to fix it.
The Error Explained
That Session has not been configured for this application or request exception means exactly what it says: your ASP.NET application hasn't been set up to use Session functionality yet. Unlike older ASP.NET frameworks (like Web Forms), ASP.NET Core doesn't enable Session by default—you have to manually add and configure the Session middleware before you can interact with HttpContext.Session.
Why Your Code Triggers It
In your POST action, you're trying to store a value in the Session with HttpContext.Session.Set(...), but since your app hasn't been configured to support Session, the runtime throws this error when it tries to access the Session object.
How to Fix It
You need to add the Session service and middleware to your application's setup. The steps depend on your ASP.NET Core version:
For ASP.NET Core 6/7/8 (Top-level statements in Program.cs)
Add the Session service before building the app:
var builder = WebApplication.CreateBuilder(args); // Add Session service (place this before AddControllers) builder.Services.AddSession(options => { // Optional: Configure Session settings options.IdleTimeout = TimeSpan.FromMinutes(30); // How long Session stays alive without activity options.Cookie.HttpOnly = true; // Blocks client-side JS access to the Session cookie (security best practice) options.Cookie.IsEssential = true; // Marks the cookie as essential for GDPR compliance }); // Add other required services builder.Services.AddControllers();Add the Session middleware in the request pipeline (order matters!):
var app = builder.Build(); app.UseHttpsRedirection(); app.UseRouting(); // Add UseSession HERE, after UseRouting but before UseAuthorization app.UseSession(); app.UseAuthorization(); app.MapControllers(); app.Run();
For Older ASP.NET Core Versions (Startup.cs)
In the
ConfigureServicesmethod:public void ConfigureServices(IServiceCollection services) { services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddMvc(); }In the
Configuremethod:public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseSession(); // Place here, before UseAuthorization/UseMvc app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
Once you've added these configurations, your code should be able to access HttpContext.Session without throwing the exception. Your login logic looks solid otherwise—just keep an eye on how you handle invalid credentials (which you're already doing with the UnauthorizedAccessException).
内容的提问来源于stack exchange,提问作者Keselme

