'Blazor + Identity: Unable to get value of User.FindFirst(ClaimTypes.NameIdentifier).Value
I've got a Blazor Webassembly app (.net 6) and it's ASP.NET Core hosted with individual accounts/Identity Server. I've scaffolded the Identity pages and have added a new folder for storing all of my pages related to user management. When editing a user, I need to be able to amend details against the user themselves (e.g. name, phone number) but also data in related tables (e.g a relationshop table that links a user to the teams they're on).
In order to make changes in the related tables, I need to be able to pass an HttpContext over to my UnitOfWork class so that it can extract the logged in user ID. To do this I'm just using the HttpContext that gets exposed as part of the PageModel class. My UnitOfWork then tries to run the following code:
var userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
However, this particular line keeps returning a null reference exception and I'm struggling to understand why. When I check the HttpContext I pass over from Edit.cshtml, it appears to be populated:
and it seems to have picked up the user:
I saw on this post that the issue might not be with the HttpContext but with the ClaimType instead, however I've added:
builder.Services.Configure<IdentityOptions>(options =>
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
in my Program.cs file, but the null reference error persists.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


