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

Luc*_*dov 1 .net asp.net-core blazor

我正在使用blazer服务器端应用程序进行测试,并尝试在.razor页面中获取登录的用户。这个

UserManager.GetUserAsync(User)
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*nty 7

如果用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>
Run Code Online (Sandbox Code Playgroud)

如果您不想使用该方法,则可以请求称为的级联参数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.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我做了什么:

  1. 将其添加到Startup.ConfigureServices
services.AddHttpContextAccessor();
Run Code Online (Sandbox Code Playgroud)
  1. 用它来获取我的 .razor 页面中的用户名,首先是这两行
@inject UserManager<WebPageUser> UserManager
@inject IHttpContextAccessor HttpContextAccessor
Run Code Online (Sandbox Code Playgroud)
  1. 然后调用显示用户名,如下所示:
<p>Hello @UserManager.GetUserName(HttpContextAccessor.HttpContext.User)</p>
Run Code Online (Sandbox Code Playgroud)