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)
What I did:
services.AddHttpContextAccessor();
@inject UserManager<WebPageUser> UserManager
@inject IHttpContextAccessor HttpContextAccessor
<p>Hello @UserManager.GetUserName(HttpContextAccessor.HttpContext.User)</p>
If you surround your code with the AuthorizeView
component you can get access to a context
object that supplies the current user.
<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>
If you don't want to use that approach you can request a cascading parameter called authenticationStateTask
, which is provided by the 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.");
}
}
}