使用Blazor Server和Identity获取用户信息的代码解法
首先,在Blazor Server应用程序中安装以下NuGet软件包:
Microsoft.AspNetCore.Authorization
Microsoft.AspNetCore.Components.Authorization
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
接下来,创建一个Identity数据库并添加一个用户:
使用以下命令创建数据库:
Add-Migration InitialCreate
Update-Database
创建一个页面,以获取用户信息。编辑“Index.razor”并添加以下代码:
@page "/"
@using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Identity
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject UserManager
@if (user != null) {
Welcome, @user.Email!
} else {You are not logged in.
}@code { private IdentityUser user;
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = await UserManager.GetUserAsync(authState.User);
if (user != null)
{
this.user = user;
}
}
}
在代码中,我们注入了AuthenticationStateProvider和UserManager服务,以获取对AuthenticationState和IdentityUser的访问。OnInitializedAsync生命周期方法用于获取用户信息并将其分配给一个私有字段“user”。
最后,我们在页面上使用该用户的信息。如果用户处于登录状态,则显示其电子邮件地址。否则,显示“您未登录”。