public async Task AddToRoleAsync(IUser user, string normalizedRoleName, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var roleNames = await _roleService.GetRoleNamesAsync(); var roleName = roleNames?.FirstOrDefault(r => NormalizeKey(r) == normalizedRoleName); if (string.IsNullOrWhiteSpace(roleName)) { throw new InvalidOperationException($"Role {normalizedRoleName} does not exist."); } var olduser = _dbcontext.Set <User>().Find(((User)user).Id); var role = (RoleInfo)(await _roleClaimStore.FindByNameAsync(normalizedRoleName, cancellationToken)); if (olduser.Roles.Count(e => e.Role.Id == role.Id) <= 0) { olduser.Roles.Add(new UserRole() { UserId = olduser.Id, RoleId = role.Id }); } _dbcontext.SaveChanges(); }
public async Task AddToRoleAsync(IUser user, string roleName, CancellationToken cancellationToken) { var rolenames = await _roleProvider.GetRoleNamesAsync(); var normalRolename = rolenames?.FirstOrDefault(e => NormalizeKey(e) == roleName); if (string.IsNullOrWhiteSpace(normalRolename)) { throw new InvalidOperationException($"角色 {normalRolename} 不存在."); } var olduser = _dbContext.Set <User>().Find(((User)user).Id); var role = (Role)(await _roleClaimStore.FindByNameAsync(normalRolename, cancellationToken)); if (olduser.Roles.Count(e => e.Role.Id == role.Id) <= 0) { olduser.Roles.Add(new UserRole() { UserId = olduser.Id, RoleId = role.Id }); } _dbContext.SaveChanges(); }
/// <summary> /// Return a role with the normalized name if it exists. /// </summary> /// <param name="normalizedRoleName">The normalized role name.</param> /// <param name="cancellationToken"> /// The <see cref="CancellationToken"/> used to propagate notifications that the operation /// should be canceled. /// </param> /// <returns>The role if it exists.</returns> protected override Task <TRole> FindRoleAsync(string normalizedRoleName, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); return(_roleStore.FindByNameAsync(normalizedRoleName, cancellationToken)); }
/// <summary> /// 查询用户组。 /// </summary> /// <param name="normalizedRoleName">用户组名称。</param> /// <param name="cancellationToken">取消标志。</param> /// <returns>返回用户组实例对象。</returns> public virtual Task <TRole> FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken = new CancellationToken()) { return(_store.FindByNameAsync(normalizedRoleName, cancellationToken)); }