【问题标题】:System.InvalidOperationException when using HttpContext.Session with use.Session(); setSystem.InvalidOperationException 将 HttpContext.Session 与 use.Session() 一起使用;放
【发布时间】:2019-12-02 10:19:01
【问题描述】:

我正在使用 Razor 页面为我的研究项目开发一个 .NET Core 3.0 应用程序。该应用程序将使用登录功能,我想使用会话发送数据并验证登录的用户。

为此,我决定在发布期间使用 HttpContext.Session 来获取和设置字符串。

当我使用线路时:HttpContext.Session.SetString("username", "test");

我收到错误:System.InvalidOperationException: 'Session has not been configured for this application or request.'

经过一番广泛的谷歌搜索并使用Microsoft doc,我似乎找不到解决方案。我到处都得到答案,我需要在我的 Startup.cs 文件中包含 services.AddSession 和 app.UseSession();,这些都添加在 'UseMvc();' 之前行。

我的选项已经用完了,我的软件老师不想给我任何帮助,除了“你使用的是正确的版本吗”,我认为我根据 Microsoft 文档这样做。

我错过了什么导致此错误?我怎样才能让会话正常工作?我是不是执行错了?

下面是我的 Startup.cs 类:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddRazorPages();
            services.AddSession(options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
                options.IdleTimeout = TimeSpan.FromSeconds(10);
            });
            services.AddMvc(option => option.EnableEndpointRouting = false);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();

            app.UseMvc();
        }
    }

值得注意的是当我在之间使用app.UseHttpContextItemsMiddleware(); app.UseSession(); 和 app.UseMvc(); 我收到一个 Intellisense 错误,指出 IApplicationBuilder 没有此方法。在 Microsoft 文档中显示此字符串包含在 Startup.cs 中。

【问题讨论】:

  • 尝试移动你的 app.UseSession();在 app.UseStaticFiles(); 之后
  • app.UseSession();已经在 app.UseStaticFiles(); 之后。扭转这个仍然会给出错误,离开 app.UseSession();在 app.UseStaticFiles(); 之前仍然给出错误。
  • 您是否尝试过在 ConfigureServices 中使用 SetCompatibilityVersion:services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);此外,您还有 app.UseStaticFiles();两次
  • 我删除了第一个 app.UseStaticFiles();并将 .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) 添加到 services.AddMvc();结果同样的错误。这也适用于版本 _2_0。

标签: c# asp.net-core


【解决方案1】:

我得到的答案是我需要包含 services.AddSession 和 app.UseSession();在我做的 Startup.cs 文件中,这些都添加在 'UseMvc();' 之前行。

是的,你是对的。但是,调用UseMvc() 或调用UseRouting()+ UseEndpoints(),但不要同时调用它们。从 ASP.NET 3.0 开始,我建议您应该使用 UseRouting()+ UseEndpoints() 而不是 UseMvc()。

在您的原始代码中,UseEndpoints() 在 UseSession() 之前触发,这使得 MVC/Razor 页面在 UseSession() 之前执行。要解决该问题,请将您的代码更改如下:

公共无效配置(IApplicationBuilder 应用程序,IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } 别的 { app.UseExceptionHandler("/错误"); } app.UseHttpsRedirection(); app.UseStaticFiles(); // 将 UseSession 放在要获取会话的行之前。 // 至少,你应该把它放在 `app.UseEndpoints(...)` 之前 app.UseSession(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(端点 => { 端点.MapRazorPages(); // 如果你需要 mvc,别忘了 // 添加 `services.AddControllersWithViews` // 并添加这一行 endpoints.MapControllerRoute( 名称:“默认控制器”, 模式:“{controller=Home}/{action=Index}/{id?}”); }); app.UseHttpsRedirection(); app.UseStaticFiles(); 应用程序.UseSession(); app.UseMvc(); }

【讨论】:

  • 这解决了我的问题!非常感谢您的修复和解释!
猜你喜欢
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多