gpt4 book ai didi

c# - Blazor 服务器应用程序。类里面的 Windows 身份验证?

转载 作者:行者123 更新时间:2023-12-03 19:03:55 24 4
gpt4 key购买 nike

我正在使用最新的 VS2019Pro 和 Core 3.1。
Blazor ServerApp 似乎在 .razor 页面的 @code{} 标记中运行了实时代码。因此,与其使用 API 来提供数据,我认为只创建类和方法来返回数据会很有意义。
我面临的唯一问题是能够在类中使用 User.Identity.Name。通常这是在 .razor 页面和 Controller 中提供的,没有问题,但是我如何(如果可能的话)在类中使用相同的 User.Identity.Name 属性?

最佳答案

您可以使用标准的 .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

关于c# - Blazor 服务器应用程序。类里面的 Windows 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64151451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com