Mar*_*per 1 asp.net-identity blazor blazor-server-side
UserManager.GetUserAsync(authState.User)UserManager除非已经被调用,否则会抛出异常。
例如;
这引发NullReferenceException了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
}
}
Run Code Online (Sandbox Code Playgroud)
但这工作正常;
@ 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
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我需要UserManager先触发才能使用该GetUsersAsync方法?
不支持它们的原因是它们仅在服务器上可用。你的问题的真正原因是你没有提供UserManager<>注射。
注:IdentityUser是用户的基类。该模板不提供继承此的ApplicationUser。
所以在Startup.cs
services.AddTransient<UserManager<ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)
@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
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1678 次 |
| 最近记录: |