I have got problem with one of helpers in my project (ASP.NET Core 7 MVC with standard MS AspNetCore.Identity authentication)
DI contains:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Helper class:
public HelperClassSample(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
// ... unrelatable code ...
var x = _httpContextAccessor.HttpContext.User
The problem is, that x
is never null, but in some cases does not contain any data in ClaimsPrincipal
. If I run the app, log out, then log in, and restart browser - everything is fine, there are proper ClaimsPrincipals
in x
.
But after another reset/rebuild, problem with empty ClaimsPrincipal
occurs. What can be the problem?
I cannot use HttpContext
from base .NET controller, since the problem occurs in a class which is not a controller. This class (HelperClassSample
) is widely used throughout a lot of layers / projects in this solution
Although this is the reality in that code base, this is typically a bad idea. As the documentation for IHttpContextAccessor states:
Not only may it make testing more difficult, but the use of Ambient Context also implies that it becomes difficult to reason about which HTTP request a particular execution thread relates to.
This may particularly be true if the code executes on a background thread.
Most likely, the problem reported in the OP is a symptom that the code executes in a context where no user is logged in.
My best advice is to keep HTTP-specific behaviour in the 'Controller layer', instead of distributing it throughout the code base.