在ASP.NET Core 2.2中的View中检查已登录的用户角色

时间:2019-02-13 01:31:14

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

我的Web应用程序中的用户可能具有来自不同应用程序的多个角色。这些角色存储在HttpContext的序列化数组中,该数组称为“角色”。

enter image description here

当前,对于我的控制器,我实现了一个自定义过滤器,该过滤器反序列化数组并像这样读取其中的项

public void OnActionExecuting(ActionExecutingContext context)
{
            string[] applications = ListOfApplications.Split(",");
            string[] roles = ListOfRoles.Split(",");
            var userRoles = context.HttpContext.User.Claims.Where(c => c.Type == "Roles").Select(c => c.Value).ToList();
            var matches = 0;
            foreach (var item in userRoles)
            {
                var currentItem = JsonConvert.DeserializeObject<UserRoleDetailsViewModel>(item);
                UserRoleDetailsViewModel urdvm = new UserRoleDetailsViewModel
                {
                    Id = currentItem.Id,
                    Name = currentItem.Name,
                    ApplicationId = currentItem.ApplicationId,
                    ApplicationName = currentItem.ApplicationName
                };
                for (var i = 0; i < applications.Length; i++)
                {
                    if(applications[i] == ApplicationGlobals.All && roles[i] == RoleGlobals.All)
                    {
                        matches++;
                    }
                    if(applications[i]== ApplicationGlobals.All && roles[i] == urdvm.Name)
                    {
                        matches++;
                    }
                    if(applications[i] == urdvm.ApplicationName && roles[i] == urdvm.Name)
                    {
                        matches++;
                    }
                }
            }
            if (matches == 0)
            {
                context.Result = new RedirectToActionResult("Index", "Home", null);
            }
}

我在控制器的顶部这样称呼它:

[Authorize]
[TypeFilter(typeof(ValidateRolesFilter), Arguments = new object[] {
        ApplicationGlobals.app1+","+ApplicationGlobals.app1
        ,RoleGlobals.SystemAdministrator+","+RoleGlobals.User
})]

但是,这仅在控制器之前有效。如何将其扩展到视图中,以便能够基于用户角色划分导航栏中的区域?这可能吗?

1 个答案:

答案 0 :(得分:0)

  

但是,这仅在控制器之前有效。如何将其扩展到视图中,以便能够基于用户角色划分导航栏中的区域?这可能吗?

是的!可能。以下是在ASP.NET Core身份中执行此操作的方法。

@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager // ApplicatonUser is the class that inherited IndentityUser
@inject UserManager<ApplicationUser> UserManager

<ul class="navbar-nav">
    @if (SignInManager.IsSignedIn(User))
    {
       // Here is navbar items for authenticated (logged in) user

       If(User.IsInRole("Admin");)
       {
           // Here is navbar items for only user with `Admin` Role
       }
    }
    else
    {
        // Here is navbar items for user if not logged in
    }
</ul>