如何在视图中仅显示用户名角色?

时间:2019-05-02 05:42:49

标签: asp.net-mvc asp.net-core

我想在ASP.NET Core的视图中显示角色。我登录到该应用程序,并获得了以下信息:{User},您好,您的权限是:{permission}。

该怎么做?我一直在寻找各种指南,但没有提及。

我尝试过:

@using Microsoft.AspNetCore.Identity
@using EarSystem.Models
@inject SignInManager<UserApp> Sign
@inject UserManager<UserApp> UserLog
@{ 
    Layout = "~/Views/Shared/_LayoutPanel.cshtml";
}
@if (User.Identity.IsAuthenticated)
{
    <div>
        <h1>Your Account:</h1>
        <ul>
            <li><b>Login:</b><p>@UserLog.GetUserName(User)</p></li>
            <li>
                @foreach (var claim in User.Claims)
                {
                    <b>Role:</b><p>@claim</p>
                }
            </li>
        </ul>
    </div>
}
else
{
    <p></p>
}

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

结果:

enter image description here

我只需要获得结果即可,用户角色是黄色的下划线。

2 个答案:

答案 0 :(得分:0)

将代码更改为

@{
  var roles = User.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToList();
}
<li>
 @foreach (var claim in roles)
 {
     <b>Role:</b><p>@claim</p>
 }

答案 1 :(得分:0)

您可以注入IHttpContextAccessor以访问视图中的当前HttpContext和用户。然后使用UserManager.GetRolesAsync(user)获得用户的所有角色。

@using Microsoft.AspNetCore.Identity
@using EarSystem.Models
@inject SignInManager<UserApp> Sign
@inject UserManager<UserApp> UserLog

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor

@{
    Layout = "~/Views/Shared/_LayoutPanel.cshtml";
}
@if (User.Identity.IsAuthenticated)
{
    var user = await UserLog.GetUserAsync(HttpContextAccessor.HttpContext.User);
    var roles = await UserLog.GetRolesAsync(user);
    <div>
        <h1>Your Account:</h1>
        <ul>
            <li><b>Login:</b><p>@UserLog.GetUserName(User)</p></li>
            <li>
                @foreach (var role in roles)
                {
                    <b>Role:</b><p>@role</p>
                }
            </li>
        </ul>
    </div>
}  

在startup.cs ConfigureServices中,注册IHttpContextAccessor

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

确保已在数据库中植入角色,并且已为注册用户分配了角色。