コード例 #1
0
        public async Task <IActionResult> ChangeRoles(ChangeRolesModel model)
        {
            var currentUser = await this.userManager.FindByEmailAsync(User.Identity.Name);

            var currentRoles = await this.userManager.GetRolesAsync(currentUser);

            // Add any new roles.
            var newRoles = model.Roles.Except(currentRoles).ToList();

            await this.userManager.AddToRolesAsync(currentUser, newRoles);

            // Remove any old roles we're no longer in.
            var removedRoles = currentRoles.Except(model.Roles).ToList();

            await this.userManager.RemoveFromRolesAsync(currentUser, removedRoles);

            // After we change roles, we need to call SignInAsync before AspNetCore Identity picks up the new roles.
            await this.signInManager.SignInAsync(currentUser, true);

            return(RedirectToAction("Index", "Home"));
        }
コード例 #2
0
        public async Task <ChangeRolesModel> GetAllRolesForUser(string userId)
        {
            var user = await userManager.FindByIdAsync(userId);

            try
            {
                var userRoles = await userManager.GetRolesAsync(user);

                var allRoles = roleManager.Roles.ToList();
                var model    = new ChangeRolesModel
                {
                    UserId    = user.Id,
                    UserEmail = user.Email,
                    UserRoles = userRoles,
                    AllRoles  = allRoles
                };

                return(model);
            }
            catch (NullReferenceException e)
            {
                throw e;
            }
        }