首页 > 解决方案 > 获取当前用户 Blazor webassembly 的 UserId

问题描述

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

方法

语境。用户身份名称

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

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

我已经搜索了网络,但是我一直看到返回的用户名。

任何帮助将不胜感激。

标签: entity-frameworkasp.net-coreblazorblazor-client-sideblazor-webassembly

解决方案


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

@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.";
        }
    }
}

推荐阅读