My Blazor Server app won't display the user name

I can’t get my Shared\LoginDisplay.razor to display the user name.

This should work…

<AuthorizeView>
	<Authorized>
			Hello @context.User.Identity.Name
	</Authorized>
	<NotAuthorized>
		<a href="@Login" class="btn btn-xs btn-outline-info float-right text-black-50">
			<u>Log in</u> <i class="fas fa-sign-in-alt"></i>
		</a>
	</NotAuthorized>
</AuthorizeView>
	

I have followed this blog but to no avail.

The app uses net6.0 framework

When I list my claims, one of the items is…
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
with the proper value of the user name, but I should get it with @context.User.Identity.Name

hope this makes sense
thanks, john

I read in one of the more recent blog posts on setting up your Blazor app that using “context” was frowned upon. I don’t know why - I’m a bit of a Blazor newb myself (not to MVC, mind you, just Blazor). But regardless, the article mentioned that you should be DI (direct injecting) access to the AuthencationState and then pulling it from there. For example, in your razor page or component:

@inject AuthencationState state;

@code {
    private string imageUrl = "";
    private string nameAndEmail = "";

    protected override async Task OnInitializedAsync()
    {
        var state = await authState.GetAuthenticationStateAsync();
        var email = Auth0Util.GetEmail(state?.User);
        var name = Auth0Util.GetName(state?.User);
        nameAndEmail = $"{name} ({email})";
        imageUrl = Auth0Util.GetImageUrl(state?.User);

        await base.OnInitializedAsync();
    }
}

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.