Get current (logged) user in ASP.NET Core 3.0 .razor page

后端 未结 2 997
后悔当初
后悔当初 2021-01-06 09:44

I\'m testing the waters with a blazer server-side app and trying to get the logged user in a .razor page. This

UserManager.GetUserAsync(User)
2条回答
  •  滥情空心
    2021-01-06 10:31

    If you surround your code with the AuthorizeView component you can get access to a context object that supplies the current user.

    
        
            

    Hello, @context.User.Identity.Name!

    You can only see this content if you're authenticated.

    Authentication Failure!

    You're not signed in.

    If you don't want to use that approach you can request a cascading parameter called authenticationStateTask, which is provided by the CascadingAuthenticationState.

    @page "/"
    
    
    
    @code {
        [CascadingParameter]
        private Task 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.");
            }
        }
    }
    

提交回复
热议问题