Reputation: 6884
UserManager.GetUserAsync(authState.User)
is throwing an exception unless UserManager
has already been called.
For example;
This throws a NullReferenceException
on await UserManager.GetUserAsync(authState.User)
;
@ page "/"
@inject UserManager<ApplicationUser> UserManager
<AuthorizeView>
...
</AuthorizeView>
@code{
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
protected async override Task OnInitializedAsync()
{
var authState = await authenticationStateTask;
var currentUser = await UserManager.GetUserAsync(authState.User); // exception here
}
}
but this works OK;
@ page "/"
@inject UserManager<ApplicationUser> UserManager
<AuthorizeView>
...
</AuthorizeView>
@code{
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
protected async override Task OnInitializedAsync()
{
var allUsers = UserManager.Users.ToList(); // hack
var authState = await authenticationStateTask;
var currentUser = await UserManager.GetUserAsync(authState.User); // this is now working OK
}
}
Why do I need to trigger UserManager
before I can use the GetUsersAsync
method?
Upvotes: 1
Views: 1963
Reputation: 45616
SignInManager<TUser>
and UserManager<TUser>
aren't supported in Razor components.
Upvotes: 2
Reputation: 14553
The reason they are not supported is they are only available on the server. The real cause of your problem here is your not providing the UserManager<>
for injection.
Note: IdentityUser
is the base class for users. The template does not provide ApplicationUser that inherits this.
So in Startup.cs
services.AddTransient<UserManager<ApplicationUser>>();
@page "/"
@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> UserManager
@currentUser?.Email
@code{
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
ApplicationUser currentUser;
protected async override Task OnInitializedAsync()
{
var authState = await authenticationStateTask;
if (authState.User.Identity.IsAuthenticated)
{
currentUser = await UserManager.GetUserAsync(authState.User); // exception was here
}
}
}
Upvotes: 5