我在我的Blazor服务器应用程序中使用基于声明的身份验证。当用户登录到我的应用程序时,我定义了一个包含特定ID的声明,以识别数据库中的用户。
现在我想根据它的值获得一个对象,我可以在我的应用程序中使用。
例如:假设我的声明的值是1。现在我需要一种方法从数据库中获取用户1的数据,并将对象注入到我的剃须刀组件/页面中,以便在我的应用程序中随时访问所有属性。我认为这可以通过某种中间件实现,但我不确定这一点。
我目前的方法是访问_Host.cshtml
文件中的HttpContext
,该文件在页面重新加载时将适当的数据加载到页面,但在使用NavLink
或NavigationManager
更改页面时则不会。
如何在每次活动页面更改时加载相关数据?
我试图调整@Hans代码,但通过使用AuthenticationStateProvider
using System.Security.Claims
using Microsoft.AspNetCore.Components.Authorization
public class ClaimsPrincipalDataService
{
private readonly AuthenticationStateProvider AuthenticationStateProvider;
private readonly DbContext DbContext;
public ClaimsPrincipalDataService(AuthenticationStateProvider AuthenticationStateProvider , DbContext DbContext)
{
this.AuthenticationStateProvider = AuthenticationStateProvider;
this.DbContext = DbContext;
}
private async Task<User> GetUserAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
var userId = user.FindFirst(ClaimTypes.NameIdentifier).Value;
return await DbContext.Users.FindAsync(userId);
}
else
{
//do something
}
}
}
添加范围
services.AddScoped<ClaimsPrincipalDataService>();
在组件中注入服务
@inject ClaimsPrincipalDataService ClaimService
@code {
private User _user;
protected override async Task OnInitializedAsync()
{
_user = await ClaimService.GetUserAsync();
}
}