DEV Community

catrina
catrina

Posted on • Originally published at catrina.me on

Making Session Variables Work in .NET Core

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, bring in the variables but how do I keep from calling these over and over: old solution was session variables 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.. and maybe I strayed, but today I came across a problem: I was able to Set session variables, but the Get was pulling null.

Why!!??

Order. Yes, you’ll see 1000 stackflow responses about order in Configure, but now in ConfigureServices (contrary to 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();

How does the error present itself? Full Post: https://www.catrina.me/making-session-variables-work-in-net-core/

Top comments (0)