【问题标题】:Blazor UserManager.GetUserAsync throwing NullReferenceExceptionBlazor UserManager.GetUserAsync 抛出 NullReferenceException
【发布时间】:2021-02-02 11:20:13
【问题描述】:

UserManager.GetUserAsync(authState.User) 抛出异常,除非 UserManager 已经被调用。

例如;

这会在await UserManager.GetUserAsync(authState.User) 上抛出一个NullReferenceException

@ 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
    }
}

但这工作正常;

@ 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
    }
}

为什么我需要触发UserManager才能使用GetUsersAsync方法?

【问题讨论】:

    标签: asp.net-identity blazor blazor-server-side


    【解决方案1】:

    它们不受支持的原因是它们仅在服务器上可用。您的问题的真正原因是您没有提供UserManager&lt;&gt; 进行注入。

    注意:IdentityUser 是用户的基类。模板不提供继承这个的 ApplicationUser。

    所以在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
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      Razor 组件不支持SignInManager&lt;TUser&gt;UserManager&lt;TUser&gt;

      See source...

      【讨论】:

      • 当。我一定已经读了大约一千遍,但它从未落地。您知道从 ClaimsPrincipal 获取 IdentityUser 的正确方法是什么吗?
      • 能否请您告诉我您想要解决的问题,我会尝试找到可行的解决方案...
      • 我试图找回IdentityUser(在网络上的大多数示例中,我已将其覆盖为ApplicationUser
      猜你喜欢
      • 2013-05-30
      • 2020-11-17
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多