Asp.net mvc 如何在视图中仅显示用户名角色?
我想在ASP.NET Core的视图中显示角色。我登录到应用程序,我有信息:Hi{User},您有权限:{permission} 怎么做?我一直在寻找各种各样的指南,但没有提到它 我试过了:Asp.net mvc 如何在视图中仅显示用户名角色?,asp.net-mvc,asp.net-core,Asp.net Mvc,Asp.net Core,我想在ASP.NET Core的视图中显示角色。我登录到应用程序,我有信息:Hi{User},您有权限:{permission} 怎么做?我一直在寻找各种各样的指南,但没有提到它 我试过了: @using Microsoft.AspNetCore.Identity @using EarSystem.Models @inject SignInManager<UserApp> Sign @inject UserManager<UserApp> UserLog @{
@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");}
}
@使用Microsoft.AspNetCore.Identity
@使用EarSystem.Models
@注入符号管理器符号
@注入用户管理器用户日志
@{
Layout=“~/Views/Shared/\u LayoutPanel.cshtml”;
}
@if(User.Identity.IsAuthenticated)
{
您的帐户:
- 登录:@UserLog.GetUserName(用户)
-
@foreach(User.Claims中的var声明)
{
角色:@claim
}
}
其他的
{
}
@节脚本{
@{wait Html.RenderPartialAsync(“_validationScript”);}
}
结果:
我只需要获得结果的用户角色,这些角色是黄色下划线。将代码更改为
@{
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>
}
@{
var roles=User.Claims.Where(c=>c.Type==ClaimTypes.Role)。选择(c=>c.Value.ToList();
}
@foreach(角色中的var索赔)
{
角色:@claim
}
您可以插入
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>
}
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();