5

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

8
  • Have you called app.useSession()? Commented Apr 13, 2019 at 15:08
  • yes. i can set session variables fine Commented Apr 13, 2019 at 15:09
  • Is the client blocking cookies? Commented Apr 13, 2019 at 15:10
  • no, this is my localhost. so there's no blocking whatsoever Commented Apr 13, 2019 at 15:12
  • 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. Commented Apr 13, 2019 at 15:19

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

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

1 Comment

It is because you need to be GDPR compliant as explained here
1

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;
        });

Comments

1

Make sure in your controller include following reference

using Microsoft.AspNetCore.Http;

1 Comment

This seems to be feedback on another answer, is that correct? This doesn't answer the original question, which was "How do I get my session to retain values in ASP.net Core 2.1?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.