Search code examples
c#asp.net-coreaspnetboilerplate

Add 'Microsoft.AspNetCore.Session': ArgumentNullException: Value cannot be null


I want to integrate the 'Microsoft.AspNetCore.Session' package into my aspnetboilerplate solution (ASP.NET Core 2.x) to use sessions.

I add the 'Microsoft.AspNetCore.Session' package to my Web.Mvc project via NuGet. Then I insert the following code into ConfigureServices method (Startup.cs):

    // Session Configuration
    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromHours(4);
        options.Cookie = new CookieBuilder { HttpOnly = true };
    });

After that I call app.UseSession() after app.UseAbp() in the Configure method (Startup.cs).

Now, if I run the application, I get the following error:

Microsoft.AspNetCore.Server.Kestrel - Connection id "0HL96OHPL754P", Request id "0HL96OHPL754P:00000001": An unhandled exception was thrown by the application. System.ArgumentNullException: Value cannot be null. Parameter name: key at Microsoft.AspNetCore.Http.Internal.RequestCookieCollection.get_Item(String key) at Microsoft.AspNetCore.Session.SessionMiddleware.d__9.MoveNext()

If I remove app.UseSession() call, the application runs correctly.

Any ideas? Please help!


Solution

  • I found a solution for my problem. Thanks juunas for your hint.

    I must change the session configuration:

    // Session Configuration
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromHours(4);
        options.Cookie.HttpOnly = true; // correct initialization
    });