Razor组件不支持
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
方法?
不支持它们的原因是它们仅在服务器上可用。您在这里遇到问题的真正原因是您没有提供用于注射的UserManager<>
。
注意: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
}
}
}
SignInManager<TUser>
和UserManager<TUser>
。
请参阅来源。。。