Blazor技术问题:如何将EF ApplicationUser传递至深层嵌套子组件
Blazor页面跳转后获取ApplicationUser的解决方法
要解决跳转后拿不到ApplicationUser来设置CreatedBy/ModifiedBy的问题,核心是从Blazor的认证体系重新获取当前用户,再转换为你的ApplicationUser实体,具体步骤如下:
1. 在目标页面注入必要服务
在/speedwalks/view/{areaId}对应的页面组件里,注入AuthenticationStateProvider和UserManager<ApplicationUser>:
@inject AuthenticationStateProvider AuthenticationStateProvider @inject UserManager<ApplicationUser> UserManager
2. 初始化时获取并转换用户
在组件初始化方法里,拿到当前认证状态,再把ClaimsPrincipal转成ApplicationUser:
private ApplicationUser currentUser; protected override async Task OnInitializedAsync() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var claimsUser = authState.User; if (claimsUser.Identity.IsAuthenticated) { currentUser = await UserManager.GetUserAsync(claimsUser); } }
3. 写数据时直接用currentUser
当需要写入数据表时,直接用获取到的currentUser来设置字段:
async Task SaveSpeedwalk() { var speedwalk = new Speedwalk { AreaId = areaId, CreatedBy = currentUser, ModifiedBy = currentUser, Created = DateTime.Now, Modified = DateTime.Now // 其他字段按需赋值 }; await speedwalkService.AddOrUpdateSpeedwalk(speedwalk); }
额外优化
如果多个页面都需要获取当前用户,不想重复写代码,可以封装一个CurrentUserService:
public class CurrentUserService { private readonly AuthenticationStateProvider _authStateProvider; private readonly UserManager<ApplicationUser> _userManager; public CurrentUserService(AuthenticationStateProvider authStateProvider, UserManager<ApplicationUser> userManager) { _authStateProvider = authStateProvider; _userManager = userManager; } public async Task<ApplicationUser> GetCurrentUserAsync() { var authState = await _authStateProvider.GetAuthenticationStateAsync(); var claimsUser = authState.User; return claimsUser.Identity.IsAuthenticated ? await _userManager.GetUserAsync(claimsUser) : null; } }
注册这个服务后,在任意页面注入CurrentUserService,直接调用GetCurrentUserAsync()就能拿到ApplicationUser。
为什么之前的方法不行?
- 级联参数只在当前组件树有效,
NavigationManager跳转后加载的是新组件树,之前的级联参数传不过去。 AuthenticationStateProvider本身返回的是ClaimsPrincipal,需要通过UserManager转成你自定义的ApplicationUser才能拿到完整的用户属性。
内容的提问来源于stack exchange,提问作者Johan Spånberg
相关产品推荐
相关产品推荐

