public async Task <IActionResult> AddToRolesAsync(string userId, AddToRolesDto dto) { if (string.IsNullOrEmpty(userId)) { throw new ArgumentException($"'{nameof(userId)}' cannot be null or empty", nameof(userId)); } if (dto is null) { throw new ArgumentNullException(nameof(dto)); } if (userId != dto.UserId) { ModelState.AddModelError(string.Empty, "无效的参数"); return(BadRequest(ModelState)); } var result = await userService.AddToRolesAsync(dto).ConfigureAwait(false); if (result.Succeeded) { return(Ok()); } ModelState.AddModelError(string.Empty, result.ErrorMessage); return(BadRequest(ModelState)); }
/// <summary> /// 为用户分配角色 /// </summary> /// <param name="userId"></param> /// <param name="roleIds"></param> /// <returns></returns> public async Task <Result> AddToRolesAsync(AddToRolesDto dto) { if (dto is null) { throw new ArgumentNullException(nameof(dto)); } var existUser = await applicationDbContext.Users.AnyAsync(e => e.Id == dto.UserId).ConfigureAwait(false); if (!existUser) { return(FailedResult("用户不存在")); } //先删除 var userRoles = applicationDbContext.UserRoles.Where(e => e.UserId == dto.UserId); applicationDbContext.UserRoles.RemoveRange(userRoles); foreach (var roleId in dto.RoleIds) { var existRole = await applicationDbContext.Roles.AnyAsync(e => e.Id == roleId).ConfigureAwait(false); if (!existRole) { return(FailedResult($"角色[{roleId}]不存在")); } await applicationDbContext.UserRoles.AddAsync(new IdentityUserRole <string> { UserId = dto.UserId, RoleId = roleId }).ConfigureAwait(false); } try { await applicationDbContext.SaveChangesAsync().ConfigureAwait(false); return(OkResult()); } catch (DbUpdateException ex) { return(FailedResult(ex)); } }