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
app.useSession()?Set-Cookieheader.