Displaying current username in _Layout view
For an ASP.Core Razor page, inject the UserManager into _Layout.cshtml
@using Microsoft.AspNetCore.Identity
@using webApp.Models
@inject UserManager<ApplicationUser> userManager
@{
Layout = "/Pages/Shared/_Layout.cshtml";
var user = await userManager.GetUserAsync(User);
var displayName = user.DisplayName;
var imagePath = user.GravatarImageUrl;
}
<h1>Manage your account</h1>
<div>
<h4>Change your account settings</h4>
<hr />
<div class="row">
<div class="col-md-3">
<img src="@imagePath" alt="Avatar" />
<h4>@displayName</h4>
<partial name="_ManageNav" />
</div>
<div class="col-md-9">
@RenderBody()
</div>
</div>
</div>
@section Scripts {
@RenderSection("Scripts", required: false)
}
You can get any information from your extended User (ApplicationUser):
// Inject SignInManager and UserManager in your _Layout.cshtml
@inject SignInManager<ApplicationUser> signInManager;
@inject UserManager<ApplicationUser> userManager;
@if (signInManager.IsSignedIn(User))
{
// Get the current logged in user
Task<ApplicationUser> GetCurrentUserAsync() => userManager.GetUserAsync(User);
var user = await GetCurrentUserAsync();
var firstName = user.FirstName;
var lastName = user.LastName;
var lastLogin = user.LastLogin;
var nationality = user.Nationality;
var phoneNumber = user.PhoneNumber;
<h4>@firstName @lastName</h4>
<h4>@lastLogin</h4>
<h4>@nationality</h4>
<h4>@phoneNumber</h4>
}
An updated answer,
in your _Layout.cshtml
:
@using System.Security.Claims
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor
@{
string name =
httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
}
You can inject the UserManager
and SignInManager
in to your view.
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
Then you can test if user login with SignInManager.IsSignedIn(User)
and show user name with UserManager.GetUserName(User)
@if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="LogOff" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
</li>
</ul>
</form>
}
PS. Also you need to add these two using
as well
@using Microsoft.AspNetCore.Identity
@using MyWebApp.Models