How do you get current user details in a Blazor component?
This code will help you to understand how to get current user details in a Blazor component.
To get current user details in a Blazor page, we need to inject the dependency IHttpContextAccessor. We need to configure the IHttpContextAccessor service in the startup.cs as follows.
[startup.cs]
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}
[index.razor]
@page "/"
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor
<h1>@UserName</h1>
@code {
public string UserName;
protected override async Task OnInitializedAsync()
{
UserName = httpContextAccessor.HttpContext.User.Identity.Name
}
}


