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

While getting the value
][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