3
votes

ASp.Net core 2.1

I set a session variable in one controller:

 public ActionResult setsession()
    {

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

      return Ok();
    }

I can see the value in session at this point when i pause the debugger after setting the session variable. Then, i try to immediately retrieve the session variable in another controller via fetch, but its always null:

   public ActionResult getsession()
    {

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

I have set a session timeout to 20 minutes (i think)

    services.AddSession(options =>
        {

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

This is my 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?}");
        });
    }

My problem is not setting session variables. I went through that nightmare. If setting the variables was a problem, .Net Core throws an exception. I've gotten past all that.

How do I get my session to retain values in ASP.net Core 2.1? Thanks

3
Have you called app.useSession()? - Llama
yes. i can set session variables fine - BoundForGlory
Is the client blocking cookies? - Llama
no, this is my localhost. so there's no blocking whatsoever - BoundForGlory
Can you check whether you get a get a cookie in the browser when you set some session value? You can check that for example by looking at the request in the browser’s developer tools and checking if the response from the server includes a Set-Cookie header. - poke

3 Answers

1
votes

As per the documentation on session state, you will need to follow three steps to enable sessions in ASP.NET Core:

To enable the session middleware, Startup must contain:

So in addition to services.AddSession() which sets up the general session services so that you can access it in general, you will also need to do services.AddDistributedMemoryCache() in order to have some place to store the data. And finally, inside Configure you will need to set up the session middleware using app.UseSession() to make sure that the session data is read when the request is being handled so that you can access the previously stored data.

1
votes

I was facing the same issue, after setting "options.Cookie.IsEssential = true;" on AddSession. everything working fine.

 services.AddSession(options => {
            options.Cookie.IsEssential = true;
        });
0
votes

I realize there is already an answer to this, however I had the same issue wherein the value saved to the session was not persisted, but managed to solve my specific issue.

I have two machines on two domains, on the one domain the session value gets saved as expected, on the other it is saved, and can retrieve it while in the save method, but from another controller/method it returns null. Figured it might be security settings.

Turns out my problem was caused by the CookiePolicyOptions in ConfigureServices: I had CheckConsentNeeded set to true. After setting it to false it was working as expected.

services.Configure<CookiePolicyOptions>(options =>
        {                
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });