Question

Session variable value is getting null in ASP.NET Core

I am setting a session variable in one method and trying to get the session variable value from the another method in a controller but its always getting null:

Here is my code:

public class HomeController : Controller
{
    public IActionResult Index()
    { 
        HttpContext.Session.SetString("Test", "Hello!");
        var message = HttpContext.Session.GetString("Test");// Here value is getting correctly
        return View();
    }

    public IActionResult About()
    {
        var message = HttpContext.Session.GetString("Test"); // This value is always getting null here

        return View();
    }
}

Here is my session configuration in Startup class:

In ConfigureServices() method:

services.Configure<CookiePolicyOptions>(options =>
{
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDistributedMemoryCache();
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession(options =>
{
    options.Cookie.Name = "TanvirArjel.Session";
    options.IdleTimeout = TimeSpan.FromDays(1);
});

In Configure() method:

app.UseSession();
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

Very strange and peculiar problem! Any help will be highly appreciated!

 46  43224  46
1 Jan 1970

Solution

 85

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!

2018-05-19

Solution

 11

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);
}
2019-07-22