首页 > 解决方案 > 会话变量立即为空..ASP.net Core

问题描述

ASP.NET 核心 2.1

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

 public ActionResult setsession()
    {

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

      return Ok();
    }

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

   public ActionResult getsession()
    {

        var fozzy =  HttpContext.Session.GetString("name");
        // fozzy is null
      return Ok(fozzy);
    }

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

    services.AddSession(options =>
        {

            options.IdleTimeout = TimeSpan.FromMinutes(20);
        });

这是我的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?}");
        });
    }

我的问题是没有设置会话变量。我经历了那个噩梦。如果设置变量有问题,.Net Core 会引发异常。我已经度过了这一切。

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

标签: c#asp.net-core

解决方案


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

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

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


推荐阅读