Live Chat Icon For mobile
Live Chat Icon

How do you 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
 }
}

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.