我使用的是最新的 VS2019Pro 和 Core 3.1。
Blazor ServerApp 似乎在 .razor 页面的 @code{} 标记内运行实时代码。因此,我认为创建类和方法来返回数据会更有意义,而不是使用 API 来提供数据。
我面临的唯一问题是能够在类中使用 User.Identity.Name 。通常这是在 .razor 页面和控制器中提供的,没有问题,但是我如何(如果可能的话)在类中使用相同的 User.Identity.Name 属性?
您可以使用标准 .net core 身份验证:https://learn.microsoft.com/en-us/aspnet/core/blazor/security/ ?view=aspnetcore-3.1
基本上你定义了一个:
[CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }
Run Code Online (Sandbox Code Playgroud)
然后你就可以等待了:
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.";
}
}
Run Code Online (Sandbox Code Playgroud)
编辑 - - -
像这样的东西??
基础组件:
[CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }
public String Username {get;set;}
protected override async Task OnInitializedAsync(){
Username = (await authenticationStateTask).User.Identity.Name;
}
Run Code Online (Sandbox Code Playgroud)
然后在其他组件中:
@inherits BaseCompomnent
@Username
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
352 次 |
最近记录: |