c# - 在 _Layout View 中显示当前用户名

标签 c# asp.net-core

我想在 _Layout View 的导航栏上显示当前的 ApplicationUsers Firstname+Lastname。我发现您可以像这样从当前的 RenderedBody Controller 传递您的 viewbag:

  private readonly IHttpContextAccessor _httpContext;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ApplicationUser _user;

    public HomeController(IHttpContextAccessor httpContextAccessor, UserManager<ApplicationUser> userManager) {
       _httpContext = httpContextAccessor;
       _userManager = userManager;
        _user = _userManager.Users.Single(u => u.Id == _httpContext.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);
    }

在 Controller 中:

public IActionResult Index()
    {

        ViewBag.Username = $"{_user.FirstName} {_user.Surname}";
        return View();
    }

终于在我的 _Layout View 中:

<strong class="font-bold">@ViewBag.Username</strong>

这种方法似乎有悖常理,并且对每个 View 来说都是一个巨大的痛苦。实现这一目标的标准是什么?

最佳答案

您可以将 UserManagerSignInManager 注入(inject)到您的 View 中。

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

然后您可以测试用户是否使用 SignInManager.IsSignedIn(User) 登录并使用 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>
}

附言。您还需要添加这两个 using

@using Microsoft.AspNetCore.Identity
@using MyWebApp.Models

关于c# - 在 _Layout View 中显示当前用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41581124/

相关文章:

c# - 从 List<List<String>> 中查找不同的元素

c# - AspNet.Core,IdentityServer 4 : Unauthorized (401) during websocket handshake with SignalR 1. 0 使用 JWT 不记名 token

asp.net-core - 如何在 Controller 中注入(inject)HttpHeader值?

c# - 变量不会在我的代码中递增/递减

c# - C#显示未读邮件数量

c# - 在 Xamarin Android 中启用 Multi-Dex 后出错

docker - 无法在 3.1 docker 容器中运行 dotnet dump - "Process 1 not running compatible .NET Core runtime"

c# - c#中的逻辑评估器(评估逻辑(&&,||)表达式)

c# - 将 C# 字节属性硬编码到模型中

c# - 手动将 url 与 .NET Core 3.0 中的注册端点匹配