Reputation: 866
In my application I want get the session variable that I stored and check if there is a user that exists. The code that I use to get the session variable is below:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Some other default code.
app.UseSession();
app.Use((context, next) =>
{
int? userId = context.Session.GetInt32("User");
// Use the variable.
return next();
});
}
When I check the variable with the debugger it is empty and in the context there is no value.
I added the following code to the Startup.cs in the method ConfigureServices() to make the session work:
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
});
If I set the session in my controller this way:
HttpContext.Session.SetInt32("User", user.Id);
And get the session variable in my controller like below.
HttpContext.Session.GetInt32("User");
This works as expected and I get my value back.
Why does this not work in the Startup.cs, and how do I fix this?
Upvotes: 0
Views: 3715
Reputation: 1391
I reconstructed your scenario and can confirm that it works as expected. I am able to access the session both in the middleware as well as the controller.
Are you sure you are setting the session variable somewhere? Even when accessing it within a middleware you need to set the variable first. If you set it in a controller the middleware will still be executed first and the session will be empty on the first request.
Also dependending on what caching mechanism you use, the session will not survive an application restart. The default mechanism is to use the DistributedMemoryCache
- it keeps the session in memory. If you are hosting your application on multiple machines behind a load balancer there might be another reason why the session is empty.
But so far your code looks absolutely valid and works on my machine.
Upvotes: 3