Session variable value is getting null in ASP.NET Core

I have had the same issue and tried the following separately and I found that either of them does work for me!

 1. options.CheckConsentNeeded = context => false;
 2. opts.Cookie.IsEssential = true; // make the session cookie Essential

However, not quite sure though, I think #1 might potentially lead to the breach of GDPR. Hence I would prefer #2.


For ASP.NET Core 2.1 and 2.2

In the ConfigureServices method of the Startup class, Set options.CheckConsentNeeded = context => false; as follows:

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;
});

Problem solved!


You can also just set Cookie.IsEssential = true as explained here: https://andrewlock.net/session-state-gdpr-and-non-essential-cookies/

There is an overload of services.AddSession() that allows you to configure SessionOptions in your Startup file. You can change various settings such as session timeout, and you can also customise the session cookie. To mark the cookie as essential, set IsEssential to true:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true; // consent required
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddSession(opts => 
    {
        opts.Cookie.IsEssential = true; // make the session cookie Essential
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}