Blazor how to get system username?

Alan 41 Reputation points
2022-08-04T19:50:01.61+00:00

Hi, I'm trying to display the username on the frontend using Blazor on .net 6. Username is the username from: command line -> set, or from task manager -> users. Something like FirstnameLastname. My Blazor program also uses Azure authentication sign in if there's a way to pull userid from that end.

So far I've tried:

Environment.UserName returns "browser"

System.Security.Principal.WindowsIdentity.GetCurrent().Name gives an error of "Windows Principal functionality is not supported on this platform"

Any help will be appreciated, thanks.

Developer technologies | .NET | Blazor
Windows for business | Windows Client for IT Pros | Devices and deployment | Configure application groups
Windows for business | Windows Server | User experience | Other
{count} votes

2 answers

Sort by: Most helpful
  1. Sreeju Nair 12,666 Reputation points
    2022-08-04T20:27:37.747+00:00

    In a Blazor App, you can get the username by the following.

    @Георгий Георгиевский .User.Identity?.Name

    In Visual studio, you can create the Blazor App, and choose individual user accounts for authentication. Visual studio will create all the neccessary files for you to start with. There is a login display component, created, and this include display the username. See the following code.

    @using Microsoft.AspNetCore.Components.Authorization  
    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication  
      
    @inject NavigationManager Navigation  
    @inject SignOutSessionStateManager SignOutManager  
      
    <AuthorizeView>  
        <Authorized>  
            <a href="authentication/profile">Hello, @context.User.Identity?.Name!</a>  
            <button class="nav-link btn btn-link" @onclick="BeginSignOut">Log out</button>  
        </Authorized>  
        <NotAuthorized>  
            <a href="authentication/register">Register</a>  
            <a href="authentication/login">Log in</a>  
        </NotAuthorized>  
    </AuthorizeView>  
      
    @code{  
        private async Task BeginSignOut(MouseEventArgs args)  
        {  
            await SignOutManager.SetSignOutState();  
            Navigation.NavigateTo("authentication/logout");  
        }  
    }  
    

  2. Alan 41 Reputation points
    2022-08-04T21:11:29.033+00:00

    Solution: I had to put Environment.UserName inside the controller in project.server... not the project.client


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.