gpt4 book ai didi

.net - 在 ASP.NET Core 3.0 .razor 页面中获取当前(登录)用户

转载 作者:行者123 更新时间:2023-12-03 17:57:45 26 4
gpt4 key购买 nike

我正在使用西装外套服务器端应用程序测试水域,并尝试在 .razor 页面中获取登录用户。这个

UserManager.GetUserAsync(User)

在 .cshtml View 中工作,但我找不到让它在 .razor 页面中工作的方法。没有要访问的“用户”属性。我将 IdentityUser 与扩展 IdentityUser 的 ApplicationUser 模型一起使用。我正在使用 AspNetCore 3.0 预览版 6。

最佳答案

如果你用 AuthorizeView 包围你的代码您可以访问 context 的组件提供当前用户的对象。

<AuthorizeView>
<Authorized>
<h1>Hello, @context.User.Identity.Name!</h1>
<p>You can only see this content if you're authenticated.</p>
</Authorized>
<NotAuthorized>
<h1>Authentication Failure!</h1>
<p>You're not signed in.</p>
</NotAuthorized>
</AuthorizeView>

如果您不想使用这种方法,您可以请求一个名为 authenticationStateTask 的级联参数。 ,由 CascadingAuthenticationState 提供.
@page "/"

<button @onclick="@LogUsername">Log username</button>

@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }

private async Task LogUsername()
{
var authState = await authenticationStateTask;
var user = authState.User;

if (user.Identity.IsAuthenticated)
{
Console.WriteLine($"{user.Identity.Name} is authenticated.");
}
else
{
Console.WriteLine("The user is NOT authenticated.");
}
}
}

关于.net - 在 ASP.NET Core 3.0 .razor 页面中获取当前(登录)用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56970377/

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