-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
I know the IHttpContext is only supposed to be set on the initial request to the server. But I am seeing some irregularities.
I am getting the _httpContextAccessor.HttpContext.User.Identity.Name
to see which user is logged in. This exists in my business logic and both my API and my CMS use this. This is getting called in a IdentityService
class which I made and is added as a scoped service. This class has a property called CurrentUser
.
public AppUser CurrentUser
{
get
{
if (_currentUser == null)
{
var identityNameClaims = _httpContextAccessor.HttpContext.User.Identity.Name;
_currentUser = _appUserRepository.Get(identityNameClaims);
}
return _currentUser;
}
}
Seeing it is added as a scoped service. Shouldn't the CurrentUser
keep its value?
When running my project locally with Visual Studio through either IIS Express or Kestrel it simply works. Every request I make in Blazor can access the user claims. I use this to display the user info on certain pages of my application. It is never null
. I confirmed this by debugging locally.
When I published it to my VPS running Windows Server 2019 Datacenter and IIS with dotnet 5.0.6 this is not the case. Initial request works and I do see the user info on the page (probably because of the pre-render by Blazor). But after that the connection is closed and I get a error in the javascript console saying that the IHttpContextAccessor
is null.
I installed remote debugger on the VPS and published my application as a debug build. I am calling the IHttpContextAccessor
directly in my App.razor
OnInitialized
method. The breakpoint hits twice, first time it is not null. Second time it hits it is null. Btw I did not know the OnInitialized
method is called twice.
So my question is, there is a difference in the environment that makes this work locally (and on a Ubuntu server I have running at home) but not on a Windows Server. What could this be, and how do I make sure it is persistent on every environment?
Also other tips on how to implement this properly are welcome.