gpt4 book ai didi

entity-framework - 获取当前用户 Blazor webassembly 的 UserId

转载 作者:行者123 更新时间:2023-12-05 08:14:17 25 4
gpt4 key购买 nike

所以我正在编写一个 Blazor webassembly 应用程序,具有 asp.ner 核心标识。我需要获取当前用户的 ID,而不是 IDenty 中的方法提供的用户名。

方法

上下文。用户.身份.名称

提供用户名,但我需要模型/表中 fk 的 ID。

我不能使用用户名,因为用户名可能会更改。

我在网上搜索过,但我一直只看到返回的用户名。

如有任何帮助,我们将不胜感激。

最佳答案

我将其与样板身份服务器一起使用:

@page "/claims"
@inject AuthenticationStateProvider AuthenticationStateProvider

<h3>ClaimsPrincipal Data</h3>

<p>@_authMessage</p>

@if (_claims.Count() > 0)
{
<table class="table">
@foreach (var claim in _claims)
{
<tr>
<td>@claim.Type</td>
<td>@claim.Value</td>
</tr>
}
</table>
}

<p>@_userId</p>

@code {
private string _authMessage;
private string _userId;
private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>();

protected override async Task OnParametersSetAsync()
{
await GetClaimsPrincipalData();
await base.OnParametersSetAsync();
}

private async Task GetClaimsPrincipalData()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;

if (user.Identity.IsAuthenticated)
{
_authMessage = $"{user.Identity.Name} is authenticated.";
_claims = user.Claims;
_userId = $"User Id: {user.FindFirst(c => c.Type == "sub")?.Value}";
}
else
{
_authMessage = "The user is NOT authenticated.";
}
}
}

关于entity-framework - 获取当前用户 Blazor webassembly 的 UserId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63104080/

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