ASP.NET Core:会话 ID 总是在变化

Zoo*_*oop 2 c# asp.net asp.net-core

今天启动了一个全新的 ASP.NET Core 站点。按照说明添加会话。我们在索引页上打印出会话 ID,它始终是唯一的。

我认为这可能是 cookie 合规性,所以我在 Chrome 的高级设置和调试器中取消了所有 cookie。但是横幅不会再次出现让我接受。

我也尝试过简单地禁用 CheckConsentNeeded,但这也没有影响。

除了上述调整外,几乎是默认项目和 MSDN 的副本:

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
            //options.Cookie.SecurePolicy = CookieSecurePolicy.Always; //require https
            // Make the session cookie essential
            options.Cookie.IsEssential = true;
        });

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


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

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

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

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

Zoo*_*oop 7

Wiktor Zychla 在第一条评论中是正确的:您必须为要粘贴的 ID 分配任何数据。

我只是将任何数据分配给控制器中的会话:

        public IActionResult Index()
        {
            HttpContext.Session.Set("What", new byte[] { 1, 2, 3, 4, 5 });
        }
Run Code Online (Sandbox Code Playgroud)

在那之后,HttpContext.Session.Id并没有改变,正如人们所预料的那样。

作为我第一次从 ASP.NET Framework 进入 ASP.NET Core,我没想到会这样,我相信我不会是最后一个!

  • 正确,我的答案不是“最佳实践”答案。这是一个“这是获得预期行为所需的最低限度”的答案。 (2认同)