我正在使用带有Core 3.1的最新VS2019Pro。
似乎Blazor ServerApp在.razor页面的@code {}标记中运行了实时代码。因此,我认为不使用API提供数据,而是创建类和方法来返回数据将很有意义。
我面临的唯一问题是能够在类中使用User.Identity.Name。通常,这在.razor页面和Controllers中都没有问题,但是我如何(如果可能的话)在类中使用相同的User.Identity.Name属性?
答案 0 :(得分:2)
您可以使用标准的.net核心身份验证:https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-3.1
基本上,您定义了:
[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
答案 1 :(得分:0)
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;
}
在启动文件中,正确的条目必须存在于services.xxx(身份服务)