You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET新手遭遇Session未配置异常,请求原因分析

What's Causing Your 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)

  1. 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();
    
  2. 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)

  1. In the ConfigureServices method:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });
    
        services.AddMvc();
    }
    
  2. In the Configure method:

    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:39:50