Share via

.NET Core 3.1 Session is not working

vijay sahu 1 Reputation point
2021-04-26T18:43:10.07+00:00

Currently I am working on .NET Core API 3.1 Application. I have a requirement to maintain the state so that I can use it later.

Below are the code that I have done in startup.cs file.

Inside ConfigureService method

            services.AddDistributedMemoryCache();  
            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.AddSession(options =>  
            {  
                //options.Cookie.Name = "ephr";  
                options.IdleTimeout = TimeSpan.FromMinutes(10);  
                options.Cookie.HttpOnly = true;  
                options.Cookie.IsEssential = true;  
            });  

And the for Configure Method

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
        {  
            app.UseMiddleware<HttpRequestBodyMiddleware>();  

            if (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  
            app.UseMiddleware<ExceptionMiddleware>();  
            app.UseRouting();  
            app.UseCors(allowSpecificOrigins);  
            app.UseAuthentication();  
            app.UseAuthorization();  
            app.UseMiddleware<JwtMiddleware>();  
            app.UseSession();  
            app.UseEndpoints(endpoints =>  
            {  
                endpoints.MapControllers();  
            });  
            app.UseSwagger();  
            app.UseSwaggerUI(c =>  
            {  
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "AS.ePHR.Business API V1");  
            });  
        }  

Set the session value using below code

HttpContext.Session.Set<string>("OTP", _accountService.GenerateOTP(authenticatResponse.Id));  

For Get value from session code is as bellow

var otpFromServer = HttpContext.Session.Get<string>("OTP");  

Problem:

Able to set the value and if immediately inspecting the session value then I can clearly see that value under session but in round trip from browser, when another api method and calling GET method of ISession extension to get the value from session it returns null value because in inspect list there is no "OTP" Session enlisted.

Can any one help me to understand why the code is working for my 3.1 .net core app..

Please find the below screen shot for more understanding and clarity

While setting the values

91402-image.png

While getting the value

![91383-image.png]2

I referred the below link to implement the same in my code.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0

Developer technologies | ASP.NET Core | Other

4 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,061 Reputation points
    2022-07-27T18:00:51.727+00:00

    I review you code again. the issue is:

                 services.AddSession(options =>  
                 {  
                     //options.Cookie.Name = "ephr";  
                     options.IdleTimeout = TimeSpan.FromMinutes(10);  
                     options.Cookie.HttpOnly = true;  
                     options.Cookie.IsEssential = true;  
                 });  
    
             app.UseCors(allowSpecificOrigins);  
    

    you are making the session cookie HttpOnly and it looks like you are using CORS. to include HttpOnly cookies, you to include credentials setting

    // XmlHttpRequest  
    const xhr = new XmlHttpRequest();  
    xhr.withCredentials = true;  
      
    // fetch  
    fetch(url,{  
       method:'post',  
       headers,  
       withCredentials: "include"     // same-origin, include, *same-origin, omit  
    });  
      
    

    Was this answer helpful?

    0 comments No comments

  2. Bruce (SqlWork.com) 84,061 Reputation points
    2022-07-05T15:47:41.69+00:00

    session support requires a cache handler to be registered as a service. you can use an in-memory or if a farm, a distributed cache

    Was this answer helpful?


  3. Ankit Jasuja 1 Reputation point
    2022-07-05T14:24:29.597+00:00

    I have the same problem in .net core 3.1.

    Did anyone find the solution?

    Was this answer helpful?

    0 comments No comments

  4. MR_MEOW 3,536 Reputation points
    2021-04-26T20:28:38+00:00

    Its out dated
    use the current version

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.