I'm using Thread to store Locale and pass it down the layers.
In my middleware I set the selected locale in the current thread as follow:
Thread.SetData(Thread.GetNamedDataSlot('SelectedLocale'), selectedLocale /* I get this value form the request */);
Then in the rest of my code, I use this line to access that data:
var selectedLocale = Thread.GetData(Thread.GetNamedDataSlot('SelectedLocale'));
However, this sometimes works, and sometimes returns null.
I used var threadId = Thread.CurrentThread.ManagedThreadId and realized that Id changes sometimes.
Why is it so? How can I make sure that I'm using the same thread during my request processing?
Update
I'm using the same technique for my APIs and for my Razor Page applications.
My APIs work just fine. They never fail.
However, my Razor Page applications fail almost 70% of the time. But they also work sometimes.
I think there must be something related to the Razor Pages here.