在 blazor 组件中获取当前用户

Getting the current user in a blazor component

我试图通过仅执行 cmd @context.User.Identity.Name 来获取在 .NET Core 5.0 上登录 Blazor 应用程序的用户,但是当我 运行 程序时它只显示“欢迎, "

然后我看到了一个潜在的解决方法,即注入 AuthenticationStateProvider 属性,调用 GetAuthenticationStateAsync 并从中获取 User

正在尝试这样做:

Index.razor:

@page "/"
@inject AuthenticationStateProvider GetAuthenticationStateAsync

<AuthorizeView>
    <Authorized>
        <h3>Welcome, <b>@name</b></h3>
    </Authorized>
    <NotAuthorized>
        <h3>You are signed out!!</h3>
    </NotAuthorized>
</AuthorizeView>

@code{

    protected override async Task OnInitializedAsync()
    {
        var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync();
        var user = authstate.User;
        var name = user.Identity.Name;
    }
}

问题是,每当我在 <h3> 中执行 @name 时,它​​都会说名称 'name' 在当前上下文中不存在。我什至尝试将 @code {} 移到 <AuthorizeView> 之前,但它仍然说同样的话。 为什么我不能调用 @name

跟进

我试图在我的 Index.razor 中执行以下操作,但这样做没有用,仍然如屏幕截图所示。任何帮助将不胜感激!

@page "/"
@inject AuthenticationStateProvider GetAuthenticationStateAsync

<AuthorizeView>
    <Authorized>
        <h3>Welcome, <b>@GetAuthenticationStateAsync.GetAuthenticationStateAsync().Result.User.Identity.Name</b></h3>
    </Authorized>
    <NotAuthorized>
        <h3>You are signed out!!</h3>
    </NotAuthorized>
</AuthorizeView>

调试尝试

第二次尝试,当我尝试使用 Rene 的建议时,我仍然得到与屏幕截图相同的结果

@page "/"
@inject AuthenticationStateProvider GetAuthenticationStateAsync

<AuthorizeView>
    <Authorized>
        <h3>Welcome, <b>@Name</b></h3>
    </Authorized>
    <NotAuthorized>
        <h3>You are signed out!!</h3>
    </NotAuthorized>
</AuthorizeView>

@code{

    private string Name;

    protected override async Task OnInitializedAsync()
    {
        var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync();
        var user = authstate.User;
        var name = user.Identity.Name;
        Name = name;
    }
}

看来您的问题可能是“@GetAuthenticationStateAsync.GetAuthenticationStateAsync().Result.User.Identity.Name”中没有存储数据。在调试中尝试 运行,在那个位置设置一个断点,看看名称中是否存储了任何值。

您的名称变量是在方法范围内声明的。 就像在 class 中一样,只需在方法覆盖上方声明一个名称 属性。然后就可以在方法中设置它的值,然后在razor中读取了。

编辑:UserManager<TUser> 在 Razor 组件中不受支持。 https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-5.0


为了识别和操作当前经过身份验证的用户,我使用 UserManager (Microsoft.AspNetCore.Identity.UserManager) 将经过身份验证的用户分配给我的 ApplicationUser 对象(我的 Blazor Server 应用程序使用 ASP.NET Core Identity ),然后我可以与我的其他实体一起进一步操作。

1、我注入 UserManager:

2,我将身份验证状态公开为级联参数,并声明一个 ClaimsPrincipal(描述当前用户)。

3、在我的 OnInitializedAsync() 方法中,我从身份验证状态获取 ClaimsPrincipal,并使用 UserManager 的 GetUserAsync() 获取返回的 ApplicationUser 对象(如果用户未通过身份验证,我也会重定向到登录):