I have a .NET Core 2.1 MVC project that I upgraded to .NET Core 3.0 in steps according to this link. The project uses IHttpContextAccessor
to store several values in the HttpContext.Session
collection and when I start the project with F5 on my development environment everything seems to be working. But when I publish the project to my test server the session key collection is empty and the values are no longer there.
Because the code should be the same on both environments I guess it must be related to how sessions are configured for the project, but I haven't been able to figure out a solution. This is how my Startup.cs
is configured:
public void ConfigureServices(IServiceCollection services)
{
...
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddDistributedMemoryCache();
services.AddSession();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseSession();
...
}
I tried serializing the Session object with Newtonsoft but the result was very limited:
{"IsAvailable":true,"Id":"44b1d511-e0cb-a1a3-c117-84033b80df25","Keys":[]}
Unfortunately the project cannot run by itself but is dependent on external input so it takes a considerable amount of time to test each scenario. Before I completely strip the project down I wanted to know if anyone might have a suggestion on what I could do to identify the cause for this.
I finally figured out what the issue was and it was a bit of a blunder. It seems I forgot to configure the cookie settings when adding session as a service in Startup.cs
. So instead of this:
services.AddSession();
it should have been this:
services.AddSession(options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.None;
options.Cookie.SameSite = SameSiteMode.None;
});
Why I got it to work on my local environment is still not answered. Maybe it had something to do with the fact that I was accessing the MVC project from a test-page on localhost (the same domain for the MVC project) but on my test server the MVC project is on a different domain. Still, everything now works like a charm.