Home > other >  Asp core sessions aren't persisting after requests ends
Asp core sessions aren't persisting after requests ends

Time:05-03

Trying to store a string in a session while waiting for confirmation from the front end, but on the next request (confirmation request) the session is completely empty.

Config

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDistributedMemoryCache();

        services.AddSession(options => {
            options.Cookie.Name = ".SingleTouch.API.Session";
            options.IdleTimeout = TimeSpan.FromMinutes(20);
            options.Cookie.IsEssential = true;
            options.Cookie.HttpOnly = true;
        });

        string allowedHosts = Configuration.GetValue<string>("AllowedHosts");
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsAllowedUrls,
                              builder =>
                              {
                                  builder.WithOrigins(allowedHosts)
                                         .AllowAnyHeader()
                                         .AllowAnyMethod();
                              });
        });

        services.AddControllersWithViews(options =>
            options.Filters.Add(new ApiExceptionFilter()));
    }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseCors(CorsAllowedUrls);
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseCookiePolicy();
        app.UseSession();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });
    }

And in one endpoint I have

_httpContextAccessor.HttpContext.Session.SetString("payEvent", "bro you good?");

and on the the following endpoint it retrieves it again

_httpContextAccessor.HttpContext.Session.GetString("payEvent");

but on retrieval, the session is empty. It's definitely being added initially because if you inspect or run GetString in the first request the value exists. Asp core 6 is in use.

CodePudding user response:

The Session has scoped lifetime, i.e. for any request you always get a new session. This is nesessary as each request can be issued by a differing user. If you want to store information for specific users, you need to do this in a singleton service.

  • Related