I am trying to grab the user that is logged in the Blazor app on .NET Core 5.0 by doing just the cmd @context.User.Identity.Name
, but when I run the program it just shows "Welcome, "
So I then saw a potential work around for this which is to Inject a AuthenticationStateProvider
property, call GetAuthenticationStateAsync
and get User
from it.
Attempting to do so:
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;
}
}
The issue is, whenever I do @name in the <h3>
it says the name 'name' does not exist in the current context. I even tried moving the @code {}
before the <AuthorizeView>
but it still says the same thing. Is there a reason why I cannot call the @name
?
FOLLOW UP
I attempted to do the following inside of my Index.razor
and doing it this way did not work, still displayed as in the screenshot. Any help would be greatly appreciated!
@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>
DEBUG ATTEMPT
SECOND ATTEMPT, I still get the same result as in the screenshot when doing this when I attempt to use Rene's suggestion
@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;
}
}