Identity角色管理五(添加用户到角色组)

引用网址:https://www.cnblogs.com/liessay/p/13213406.html

官方网址:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-6.0&tabs=visual-studio

因需要在用户列表中点详情按钮来到当前页,所以需要展示分组详情,并展示当前所属角色组的用户

复制代码
 public async Task<ActionResult> Details(string id)
 {
     //查找是否存在角色组
     var role = await _roleManager.FindByIdAsync(id);
     //如果角色不存在跳转回角色列表
     if (role == null)
     {
         return RedirectToAction(nameof(Index));
     }
     //给视图模型赋值
     var roleUserViewModel = new RoleUserViewModel()
     {
         RoleId = role.Id,
         RoleName = role.Name
     };
     //找出所有用户
     var users = await _userManager.Users.AsNoTracking().ToListAsync();
     //循环查找用户是否存在当前角色组
     foreach (var item in users)
     {
         if (await _userManager.IsInRoleAsync(item, role.Name))
         {
             roleUserViewModel.Users.Add(item);
         }
     }
     return View(roleUserViewModel);
 }
复制代码

详情展示页视图代码如下

复制代码
@model Shop.ViewModel.RoleUserViewModel

@{
    ViewData["Title"] = "Details";
}

<h1>Details</h1>

<div>
    <h4>CreateRoleViewModel</h4>
    <hr />
    <dl class="row">
        <dt class="col-sm-5">
            @Html.DisplayFor(model => model.RoleId)
        </dt>
        <dd class="col-sm-2">
            @Html.DisplayFor(model => model.RoleName)
        </dd>
    </dl>
    <dl class="row">
        @foreach (var item in Model.Users)
        {
            <dt>@item.UserName</dt>
        }
    </dl>
    <a asp-action="AddUserToRole" asp-route-id="@Model.RoleId" class="btn btn-success">添加用户到角色</a>

</div>
<div>
    @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
    <a asp-action="Index">Back to List</a>
</div>
复制代码

创建UserRoleViewModel模型类

复制代码
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;

namespace Shop.ViewModel
{
    public class UserRoleViewModel
    {
        public UserRoleViewModel()
        {
            Users = new List<IdentityUser>();
        }
        public string RoleId { get; set; }
        public string UserId { get; set; }
        public List<IdentityUser> Users { get; set; }
    }
}
复制代码

在role控制器中创建添加用户到角色组的显示方法

复制代码
public async Task<ActionResult> AddUserToRole(string id)
{
    //查找是否存在角色
    var role = await _roleManager.FindByIdAsync(id);
    //如果角色不存在跳回角色列表
    if (role == null)
    {
        return RedirectToAction(nameof(Index));
    }
    //将查找的角色ID添加到视图模型
    var userRoleViewModel = new UserRoleViewModel()
    {
        RoleId = role.Id
    };
    //将所有用户找出来
    var users = await _userManager.Users.AsNoTracking().ToListAsync();
    //循环遍历是否用户不在当前角色中、
    foreach (var item in users)
    {
        if (!await _userManager.IsInRoleAsync(item, role.Name))
        {
            userRoleViewModel.Users.Add(item);
        }
    }
    //将视图模型返回
    return View(userRoleViewModel);
}
复制代码

根据选择添加用户到角色组

复制代码
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddUserToRole(UserRoleViewModel input)
{
    //查找当前用户
    var user = await _userManager.FindByIdAsync(input.UserId);
    //查找当前角色组
    var role = await _roleManager.FindByIdAsync(input.RoleId);
    //角色跟用户都找到
    if (user != null && role != null)
    {
        //用户管理中添加当前用户到角色组(当前用户,角色组名称)
        var result = await _userManager.AddToRoleAsync(user, role.Name);
        if (result.Succeeded)
        {
            return RedirectToAction(nameof(Index));
        }
        //输出所有Model级错误
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }
    }
    return View(input);
}
复制代码

页面显示,选择后按添加执行上边方法写入数据库

添加后返回详情页,并显示当前角色组的用户如图所示

添加用户后,再次添加将不再显示在选择框内

删除角色跟添加角色类似,删除代码为_userManager.RemoveFromRoleAsync(user,role.Name)

 
分类: Identity4
posted @ 2022-03-16 09:36  MaxBruce  阅读(157)  评论(0)    收藏  举报