我正在使用最新的VS2019Pro与Core 3.1。
Blazor ServerApp似乎在.razor页面的@code{}标记中运行实时代码。因此,我认为,与其使用API提供数据,创建返回数据的类和方法会更有意义。
唯一的问题是,在类中能否使用User.Identity.Name属性。通常情况下,在.razor页面和控制器中都可以轻松地提供它,但我该如何(如果可能的话)在类中使用相同的User.Identity.Name属性呢?
[CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }
那么您可以等待它:
private async Task LogUsername()
{
var authState = await authenticationStateTask;
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
_authMessage = $"{user.Identity.Name} is authenticated.";
}
else
{
_authMessage = "The user is NOT authenticated.";
}
}
编辑 -----
像这样吗?
基础组件:
[CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }
public String Username {get;set;}
protected override async Task OnInitializedAsync(){
Username = (await authenticationStateTask).User.Identity.Name;
}
然后在您的其他组件中:
@inherits BaseCompomnent
@Username
IMyRoleManager _myRoleManager;
private AuthenticationStateProvider _authenticationStateProvider;
public MyRepository(IMyRoleManager myRoleManager, AuthenticationStateProvider authentication)
{
_myRoleManager = myRoleManager;
_authenticationStateProvider = authentication;
}
public async Task<bool> AddRoleToUser(string role)
{
var id = await GetUserIdFromAuthenticationStateProviderAsync();
var result = await _myRoleManager.SetRoleForUser(role, id);
return result;
}