会话变量立即为空..ASP.net Core

Bou*_*ory 5 c# asp.net-core

ASp.Net核心2.1

我在一个控制器中设置了一个会话变量:

 public ActionResult setsession()
    {

       HttpContext.Session.SetString("name","Fozzy");

      return Ok();
    }
Run Code Online (Sandbox Code Playgroud)

当我在设置会话变量后暂停调试器时,我可以看到会话中的值。然后,我尝试立即通过 fetch 检索另一个控制器中的会话变量,但它始终为空:

   public ActionResult getsession()
    {

        var fozzy =  HttpContext.Session.GetString("name");
        // fozzy is null
      return Ok(fozzy);
    }
Run Code Online (Sandbox Code Playgroud)

我已将会话超时设置为 20 分钟(我认为)

    services.AddSession(options =>
        {

            options.IdleTimeout = TimeSpan.FromMinutes(20);
        });
Run Code Online (Sandbox Code Playgroud)

这是我的startup.cs:

      public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", builder =>
                builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
        });

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {

            options.IdleTimeout = TimeSpan.FromMinutes(20);
        });
        services.AddMvc().AddSessionStateTempDataProvider();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors("CorsPolicy");
        app.UseSession();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(name: "spa-fallback",
                defaults: new { controller = "values", action = "Get" });
        });
        //if (env.IsDevelopment())
        //{
        //    app.UseDeveloperExceptionPage();
        //}
        //else
        //{
        //    app.UseExceptionHandler("/Home/Error");
        //    app.UseHsts();
        //}

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
Run Code Online (Sandbox Code Playgroud)

我的问题不是设置会话变量。我经历了那个噩梦。如果设置变量出现问题,.Net Core 会抛出异常。我已经克服了这一切。

如何让我的会话保留 ASP.net Core 2.1 中的值?谢谢

pok*_*oke 2

根据有关会话状态的文档,您需要执行三个步骤才能在 ASP.NET Core 中启用会话:

要启用会话中间件,启动必须包含:

因此,除了services.AddSession()设置通用会话服务以便您可以一般访问它之外,您还需要做services.AddDistributedMemoryCache()一些事情以便有地方存储数据。最后,在内部Configure您需要设置会话中间件,app.UseSession()以确保在处理请求时读取会话数据,以便您可以访问之前存储的数据。