question

vijaysahu-6397 avatar image
0 Votes"
vijaysahu-6397 asked Bruce-SqlWork answered

.NET Core 3.1 Session is not working

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://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0

dotnet-aspnet-core-generaldotnet-aspnet-core-webapi
image.png (34.1 KiB)
image.png (31.4 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The code looks like a Web API application. Typically, Web API clients are stateless do not expect a cookie. Session is a feature found in UI based applications that use a browser.

0 Votes 0 ·
BC-7626 avatar image
0 Votes"
BC-7626 answered AgaveJoe commented

Its out dated
use the current version

· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The version has nothing to do with the issue. Web API is stateless. Any Web API client will not expect a cookie.

0 Votes 0 ·

Even it's working if I am testing with Swagger but once I start hitting API from Angular app then it's not maintaining the session.

0 Votes 0 ·

You are not listening. You accessed Swagger using a browser which knows how to handle cookies automatically. The Angular client does not expect a cookie. I'm not an Angular expert but a quick Google shows you must enable cookie. If you are using the HttpClient then you need withCredentials = true.

Your design is approach non-standard. Look into using local storage to persist state or a bearer token. An Angular support site is probably a better place to get help with Angular.

0 Votes 0 ·

Yes and it's the latest version only.... and same code is working when I am creating a fresh new .net core 3.1 project and enable the session... but not in current one.

0 Votes 0 ·
AnkitJasuja-8658 avatar image
0 Votes"
AnkitJasuja-8658 answered AnkitJasuja-8658 published

I have the same problem in .net core 3.1.

Did anyone find the solution?

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered AnkitJasuja-8658 commented

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


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Any example would be much appreciated.

0 Votes 0 ·
Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered

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
 });
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.