asp.net-core-identityasp.net-core-mvc-2.0

How to get Asp.net Core Identity User in View


In Asp.net core mvc project, how to get the current IdentityUser information in View ?


Solution

  • What @rdhainaut said works OK if you just want to display the username on the View. If that's all you need, you can even use the following without the needs of injecting anything!

    @if (User.Identity.IsAuthenticated)
    {
        <div>Hello, @User.Identity.Name</div>
    }
    

    The reason is, with the default configuration (assuming you're using username), the username is stored in @User.Identity.Name after successful signin.

    Now if you do want to display additional information about the logged in user, such as display name on your site top navigation, that's when I think ViewComponent` comes into play!

    For example, let's say you have defined an Admin area in your MVC project and you want to create a top navigation bar.

    1. You create a folded called ViewComponents under Admin folder.
    2. Create a view component called TopNavbarViewComponent.cs.

      public class TopNavbarViewComponent : ViewComponent
      {
          private readonly UserManager<IdentityUser> _userManager;
      
          // You can inject anything you want here
          public TopNavbarViewComponent(UserManager<IdentityUser> userManager)
          {
              _userManager = userManager;
          }
      
          public async Task<IViewComponentResult> InvokeAsync()
          {
              var appUser = await _userManager.FindByNameAsync(
                  HttpContext.User.Identity.Name);
      
              var vm = new TopNavbarViewModel
              {
                  // Just as an example... perhaps you have additional 
                  // property like FirstName and LastName in your IdentityUser.
                  DisplayName = appUser?.DisplayName,
                  Email = appUser?.Email,
                  Phone = appUser?.PhoneNumber
              };
      
              return View(vm);
          }
      }
      
    3. Define the model behind the view undler ViewComponents\Models.

      public class TopNavbarViewModel
      {
          public string DisplayName { get; set; }
          public string Email { get; set; }
          public string Phone { get; set; }
      }
      
    4. Define the view for the view component, which needs to be under Areas\Admin\Views\Shared\Components\TopNavbar\Default.cshtml by convention.

      @model Web.UI.Areas.Admin.ViewComponents.Models.TopNavbarViewModel
      
      <nav class="navbar navbar-light">
          <ul class="navbar-nav">
              <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown">
                  Hello, @Model.DisplayName
              </a>
          </ul>
      </nav>