Making Session Variables Work in .NET Core

The Problem

As noted, I work with Legacy and often have to bring in variables from the API that must be sustained across session.. (and I’m sure there might be a better way, comment and advise!).  Where I am at now, is I query the API and bring in the variables, but how do I keep from calling these over and over?  The old solution was session variables and so, that’s where I am at.

When I started to do this on Core, the most helpful article was this (and it’s in my comments):

https://adamstorr.azurewebsites.net/blog/are-you-registering-ihttpcontextaccessor-correctly

He leads you through the basic setup of a HttpContext helper class (that I still use today) and how to configure the startup..  Today, though, I came across a problem: I was able to Set session variables, but the Get was pulling null.

The Reason

Order.  Yes, you’ll see 1000 stackflow responses about order in Configure (and I was careful to do this in that method), but now in ConfigureServices (contrary to the example, as I am now using Core 2.2?), order again comes into play:

public void ConfigureServices(IServiceCollection services)
{
    //this MUST be before add mvc or session returns null
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddMvc();

Identify It

How does the error present itself?  Debugging looks great, queries to API fine, setting session (cookies) fine,  result unexpected, but..  no errors.  Trace your Get.  My Session.GetString was pulling null.

Solution

Switch order  in ConfigureServices and all was fine.

 

 

 

Continue Reading