The default project template creates a partial view _LoginPartial.cshtml which contains a bit of logic for finding out whether the user is logged in or not and find out its user name.
Since a view component might be a better fit (as there is logic involved and even 2 services injected) the following example shows how to convert the LoginPartial into a view component.
View Component class
public class LoginViewComponent : ViewComponent
{
private readonly SignInManager<ApplicationUser> signInManager;
private readonly UserManager<ApplicationUser> userManager;
public LoginViewComponent(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager)
{
this.signInManager = signInManager;
this.userManager = userManager;
}
public async Task<IViewComponentResult> InvokeAsync()
{
if (signInManager.IsSignedIn(this.User as ClaimsPrincipal))
{
return View("SignedIn", await userManager.GetUserAsync(this.User as ClaimsPrincipal));
}
return View("SignedOut");
}
}
SignedIn view (in ~/Views/Shared/Components/Login/SignedIn.cshtml)
@model WebApplication1.Models.ApplicationUser
<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 @Model.UserName!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
</li>
</ul>
</form>
SignedOut view (in ~/Views/Shared/Components/Login/SignedOut.cshtml)
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
Invocation from _Layout.cshtml
@await Component.InvokeAsync("Login")