Mark Cooper
Mark Cooper

Reputation: 6884

Blazor UserManager.GetUserAsync throwing NullReferenceException

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

Answers (2)

enet
enet

Reputation: 45616

SignInManager<TUser> and UserManager<TUser> aren't supported in Razor components.

See source...

Upvotes: 2

Brian Parker
Brian Parker

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

Related Questions