当前位置: 首页>>代码示例>>C#>>正文


C# UserManager.AddToRoleAsync方法代码示例

本文整理汇总了C#中UserManager.AddToRoleAsync方法的典型用法代码示例。如果您正苦于以下问题:C# UserManager.AddToRoleAsync方法的具体用法?C# UserManager.AddToRoleAsync怎么用?C# UserManager.AddToRoleAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在UserManager的用法示例。


在下文中一共展示了UserManager.AddToRoleAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddUserToRole

            public static async Task<IdentityResult> AddUserToRole(string userId, string roleName)
            {
                var userManager = new UserManager<PlatformUser>(
                    new UserStore<PlatformUser>(new PlatformUserIdentityDbContext()));

                //Allows for use of email address as username:
                userManager.UserValidator = new UserValidator<PlatformUser>(userManager) { AllowOnlyAlphanumericUserNames = false };

                var result = await userManager.AddToRoleAsync(userId, roleName);

                return result;
        }
开发者ID:Kazual,项目名称:Multiple-ASPNET-Identity-Contexts,代码行数:12,代码来源:ManagePlatformUsers.cs

示例2: Promote

        public ActionResult Promote(string id)
        {
            var store = new UserStore<User>(this.Data.Context);
            var manager = new UserManager<User>(store);

            manager.AddToRoleAsync(id, GlobalConstants.AdminRole);

            this.Notify(GlobalConstants.PromoteUser, NotificationType.success);

            return this.RedirectToAction("Manage");
        }
开发者ID:DimitarBakardzhiev,项目名称:NelitaBeautyStudio,代码行数:11,代码来源:RolesController.cs

示例3: ClaimsIdentityTest

        public async Task ClaimsIdentityTest()
        {
            var db = UnitTestHelper.CreateDefaultDb();
            var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
            var role = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
            var user = new IdentityUser("Hao");
            UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
            UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Admin")));
            UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Local")));
            UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Admin"));
            UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Local"));
            Claim[] userClaims =
            {
                new Claim("Whatever", "Value"),
                new Claim("Whatever2", "Value2")
            };
            foreach (var c in userClaims)
            {
                UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
            }

            var identity = await manager.CreateIdentityAsync(user, "test");
            var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory<IdentityUser, string>;
            Assert.NotNull(claimsFactory);
            var claims = identity.Claims;
            Assert.NotNull(claims);
            Assert.True(
                claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName));
            Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id));
            Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin"));
            Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local"));
            Assert.True(
                claims.Any(
                    c =>
                        c.Type == ClaimsIdentityFactory<IdentityUser>.IdentityProviderClaimType &&
                        c.Value == ClaimsIdentityFactory<IdentityUser>.DefaultIdentityProviderClaimValue));
            foreach (var cl in userClaims)
            {
                Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
            }
        }
开发者ID:tomi85,项目名称:aspnetidentity,代码行数:41,代码来源:ClaimsIdentityFactoryTest.cs

示例4: CreateUserIfNotExist

 private static async System.Threading.Tasks.Task CreateUserIfNotExist(UserManager<ApplicationUser> userManager, string email, string password, string role, string loginProvider = null, string providerKey = null)
 {
     var user = await userManager.FindByEmailAsync(email);
     if (user == null)
     {
         user = new ApplicationUser { UserName = email, Email = email };
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
 }
开发者ID:Anderman,项目名称:Mvc.JQuery.Datatables,代码行数:18,代码来源:ApplicationExtensions.cs

示例5: CreateUserIfNotExist

 private static async Task<ApplicationUser> CreateUserIfNotExist(UserManager<ApplicationUser> userManager, ApplicationUser user, string password, string role, string loginProvider = null, string providerKey = null)
 {
     //Debugger.Launch();
     user.EmailConfirmed = true;
     user.Email = user.Email ?? user.UserName;
     if (await userManager.FindByEmailAsync(user.Email) == null)
     {
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
     return user;
 }
开发者ID:Pietervdw,项目名称:DBC,代码行数:20,代码来源:ApplicationExtensions.cs

示例6: Seed

        private async void Seed()
        {
            const string roleName = "administrator";
            const string userName = "[email protected]";
            var userContext = new ApplicationDbContext();
            var roleStore = new RoleStore<IdentityRole>(userContext);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            if (roleManager.RoleExists(roleName)) return;
            await roleManager.CreateAsync(new IdentityRole(roleName));
            var userStore = new UserStore<ApplicationUser>(userContext);
            var userManager = new UserManager<ApplicationUser>(userStore);
            var admin = new ApplicationUser() {UserName = userName};
            await userManager.CreateAsync(admin, "Koekoek!IsNummer1");
            await userManager.AddToRoleAsync(admin.Id, roleName);

            var pandContext = new ExclimmoContext();
            pandContext.SeedPanden();

        }
开发者ID:johntjampens,项目名称:Exclimmo2016,代码行数:20,代码来源:Global.asax.cs

示例7: AddUserToRole

        public async Task<ActionResult> AddUserToRole(AddUserToRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var ctx = new ApplicationDbContext())
                {
                    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx));
                    var identityResult = await userManager.AddToRoleAsync(model.UserId, model.RoleName);

                    if (identityResult.Succeeded)
                    {
                        TempData["Message"] = "User added to role succesfully";
                    }
                    else
                    {
                        // TODO: add errors to TempData
                    }
                }
            }

            return RedirectToAction("EditMembers", "Roles", new { Id = model.RoleName});
        }
开发者ID:htuomola,项目名称:linx,代码行数:22,代码来源:RolesController.cs

示例8: UpdateRuoloUtente

        public async Task<IHttpActionResult> UpdateRuoloUtente(UpdateRuoloUtenteModel Model)
        {
            if (Model == null || !ModelState.IsValid)
                return BadRequest(ModelState);

            using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
            {
                var utente = await userManager.FindByNameAsync(Model.Username);
                if (utente == null)
                    return NotFound();

                if (Model.NuovoStato)
                {
                    await userManager.AddToRoleAsync(utente.Id, Model.Ruolo);
                }
                else
                {
                    await userManager.RemoveFromRoleAsync(utente.Id, Model.Ruolo);
                }
            }

            return Ok();
        }
开发者ID:Simone000,项目名称:SPA_Template,代码行数:23,代码来源:AdminController.cs

示例9: EnsureDatabaseAsync

		public async Task EnsureDatabaseAsync()
		{
			await MigrateDatabaseAsync(ServiceProvider);
			_userManager = ServiceProvider.GetService<UserManager<ApplicationUser>>();
			var roleManager = ServiceProvider.GetService<RoleManager<IdentityRole>>();
			await EnsureUsersAsync(false);
			Context = ServiceProvider.GetRequiredService<ApplicationDbContext>();
			//var userStore = new UserStore<ApplicationUser>(context);
			////var roleManager = new RoleManager<IdentityRole>();
			//var userManager = new UserManager<ApplicationUser>(
			//	, );
			EnsureDatabaseExists();
			Context.Database.EnsureCreated();
			// Add Mvc.Client to the known applications.
			_productsCrud = new CrudBase<Product, int>(
				Context, Context.Products, p => p.ProductId);
			_ordersCrud = new CrudBase<Order, int>(
				Context, Context.Orders, p => p.Id);
			var customersCrud = new CrudBase<Customer, int>(
				Context, Context.Customers, p => p.CustomerId);

			//Action<string, double, int?, DateTime?, string> prod = (name, price, customerId, dateCreated, cratedByUserId) =>
			//{
			//	productId = Prod(productsCrud, productId, name, price, customerId, dateCreated, cratedByUserId);
			//};
			Action<string, string, string> cust = (guid, firstName, lastName) =>
			{
				customersCrud.EnsureEntity(
					guid, customer =>
					{
						customer.FirstName = firstName;
						customer.LastName = lastName;
					});
			};

			cust("6c13ec25-b9cf-4c99-87e7-13a45a034342", "Harry", "Whitburn");
			cust("0e941f32-8ae1-4eae-875a-f748bae3ce2a", "Nick", "Lawden");
			cust("134bd420-f64a-40db-bbe4-0b9a9ff3eb01", "Emil", "Roijer");
			Context.SaveChanges();
			Prod("00d5c0b0-738d-41ff-86d4-dca84da1d4d5", "Apple number1", 10, null, null);
			Prod("cd4c554d-3ca2-49aa-9286-08abacba3fa0", "Apple number1", 10, 1, null, "1");
			Prod("d100c753-3335-439c-88db-b8d9b6c09cc8", "Orange number1", 20, null, null);
			Prod("da93b8a4-4378-4ce0-918e-653f1bd4acaf", "Peanut butter number1", 25, 2, null);
			Prod("fe208521-4a77-4b09-94c2-2f08a4dd8872", "xApple number2", 10, 1, null);
			Prod("844fbc16-3d77-4421-9498-aa65300bc789", "xOrange number2", 20, 2, null);
			Prod("78509968-0073-4c57-8774-ec0d58ea7ff3", "xPeanut butter number2", 25, 2, null);
			Prod("18b8c4e7-48a2-40c7-bea8-1d1879bf852e", "xApple number2", 10, 1, null);
			Prod("e5ab744c-441c-447b-ae92-055b1bce5541", "xOrange number2", 20, 2, null);
			Prod("3a5476b1-7dd8-40b0-a6ce-b6bd3127da6f", "xPeanut butter number2", 25, 2, null);
			Prod("633a125c-1fe2-4f06-859d-a8d8fd52eb11", "xApple number2", 10, 1, null);
			Prod("27eea6ff-c4aa-44a0-84fe-32b0e13beec4", "xOrange number2", 20, 2, null);
			Prod("dcdc6836-3b44-41c5-8ade-792e39ce2112", "xPeanut butter number2", 25, 2, null);
			Prod("fdc3139d-8585-4b34-b815-13598bf55791", "xApple number2", 10, 1, null);
			Prod("46b058b2-dd55-4741-9ee0-99c63c4bd94a", "xOrange number2", 20, 2, null);
			Prod("11c0e3e5-c5d7-4ff5-ba6c-a54b77f91d1b", "xPeanut butter number2", 25, 2, null);
			Prod("796b6b1d-2d6d-413c-bcab-2659c0fdf02f", "Apple number3", 10, 1, null);
			Prod("5f928f2f-bc1b-4e73-a0d8-20c36f817342", "Orange number3", 20, 2, null);
			Prod("f4fa623d-f412-4b68-8a26-17cfa16cb0a0", "Peanut butter number3", 25, 2, null);
			Prod("8f81d6ab-4c8f-4800-aea0-3cb1ca116fc6", "Apple number4", 10, 1, null);
			Prod("f2b8032f-c8ac-406f-8038-939201771901", "Orange number4", 20, 2, null);
			Prod("dc872dbf-956c-43aa-aba4-e75395af7d83", "Peanut butter number4", 25, 2, null);
			Prod("4ca16ce0-1466-4ba6-a69b-5465ed0a4b1d", "Apple number5", 10, 1, null);
			Prod("66cc487b-2eb1-470b-98c8-03ee913d860e", "Orange number5", 20, 2, null);
			Prod("e77e6589-1dba-4c8b-97b1-1564056ddf10", "Peanut butter number5", 25, 2, null);
			Prod("183946f3-41a9-4140-a1cb-b328e3a778d1", "Apple number6", 10, 1, null);
			Prod("2995edec-ec1b-42ed-aa97-1e68a9ef765c", "Orange number6", 20, 2, null);
			Prod("a78204ae-169a-4d30-936b-034cda5abd0f", "Peanut butter number6", 25, 2, null);
			Context.SaveChanges();
			Order("31d57282-4824-4441-9bd0-49588b952728", "First order", 1);
			Order("fc41cc01-6dc3-4ca5-88a4-c4a463cd6316", "Second order", 1);
			Order("f1379562-c779-43bc-a507-71a8506ca8c9", "Third order", 1);
			Context.SaveChanges();
			await EnsureUsersAsync(true);
			await roleManager.CreateAsync(new IdentityRole("Admin"));
			await roleManager.CreateAsync(new IdentityRole("User"));
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "Admin");
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "User");
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("2"), "User");
		}
开发者ID:joshcomley,项目名称:WebApi,代码行数:79,代码来源:Seeder.cs

示例10: Create

        public async Task<ActionResult>  Create(RegisterViewModel userViewModel, string RoleId, [Bind(Include="Name")] ApplicationUser kUser, string[] selectedKPIs)
        {
          
            if(selectedKPIs != null)
            {
                kUser.KPIs = new List<KPI>();
                foreach(var kpi in selectedKPIs){
                    var kpiToAdd = context.KPIs.Find(int.Parse(kpi));
                    kUser.KPIs.Add(kpiToAdd);

                }
            }
            
            if (ModelState.IsValid)
            {
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                var userinfo = new MyUserInfo()
                {
                    FirstName = userViewModel.FirstName,
                    LastName = userViewModel.LastName
                };
                var user = new ApplicationUser();
                user.UserName = userViewModel.UserName;
                user.Email = userViewModel.Email;
                user.MyUserInfo = userinfo;
                var adminresult =  UserManager.Create(user, userViewModel.Password);
         
                context.Users.Add(user);
                context.SaveChanges();
              
    
                //Add User Admin to Role Admin
                if (adminresult.Succeeded)
                {
                    if (!String.IsNullOrEmpty(RoleId))
                    {
                        //Find Role Admin
                        var role = await RoleManager.FindByIdAsync(RoleId);
                        var result = await UserManager.AddToRoleAsync(user.Id, role.Name);
                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First().ToString());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name");
                            return View();
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First().ToString());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
                    return View();

                }
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
                return View();
            }
        }
开发者ID:jgnn7,项目名称:CS451RProject,代码行数:62,代码来源:UserAdminController.cs

示例11: DatabaseInitData

        public static void DatabaseInitData(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            if (!dbContext.Users.Any())
            {
                var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" };
                var result = userManager.CreateAsync(user, "[email protected]");

                userManager.AddToRoleAsync(user, RoleNames.Admin);
            }
            if (!dbContext.Cities.Any())
            {
                dbContext.Cities.Add(new City {Name = "Рязань"});
                dbContext.Cities.Add(new City {Name = "Тула"});

                dbContext.SaveChanges();
            }

            if (!dbContext.TypesHousing.Any())
            {
                var houseTypes = new List<TypesHousing>
                {
                    new TypesHousing {Name = "1-к квартира"},
                    new TypesHousing {Name = "2-к квартира"},
                    new TypesHousing {Name = "3-к квартира"},
                    new TypesHousing {Name = "4-к квартира"},
                    new TypesHousing {Name = "5-к квартира"},
                    new TypesHousing {Name = "комната"},
                    new TypesHousing {Name = "коммуналка"}
                };


                var additionList = new string[]
                {
                    "Дом",
                    "Флигель",
                    "Гостинка",
                    "Малосемейка",
                    "Комната в общежитии",
                    "Койко-место",
                    "Коттедж",
                    "Особняк",
                    "Часть дома",
                    "Комната в секции"
                };

                foreach (var item in additionList)
                {
                    houseTypes.Add(new TypesHousing {Name = item });
                }

                foreach (var type in houseTypes)
                {
                    dbContext.TypesHousing.Add(type);
                }

                dbContext.SaveChanges();
            }

            if (!dbContext.Districts.Any())
            {
                var ryazan = dbContext.Cities.First(x => x.Id == 1);
                var tula = dbContext.Cities.First(x => x.Id == 2);
                var districs = new District[]
                    {
                        new District { Name = "Дашково Песочня", City = ryazan },
                         new District { Name = "Дягилево", City = ryazan},
                         new District { Name = "Кальное", City = ryazan},
                         new District { Name = "Канищево", City = ryazan},
                        new District { Name =  "Михайловское шоссе", City = ryazan},
                        new District { Name =  "Московский", City = ryazan},
                         new District { Name = "Недостоево", City = ryazan},
                         new District { Name = "Приокский", City = ryazan},
                        new District { Name =  "Роща", City = ryazan},
                        new District { Name =  "Рыбное", City = ryazan},
                        new District { Name =  "Рязанский р-н", City = ryazan},
                        new District { Name =  "Соколовка", City = ryazan},
                        new District { Name =  "Солотча", City = tula},
                        new District { Name =  "Центр", City = tula},
                        new District { Name =  "Шлаковый", City = tula},
                         new District { Name = "Южный", City = tula},
                         new District { Name = "Центральный р-н", City = tula},
                         new District { Name = "Советский р-н", City = tula},
                         new District { Name = "Привокзальный р-н", City = tula},
                         new District { Name = "Зареченский р-н", City = tula},
                        new District { Name =  "Пролетарский р-н", City = tula},
                        new District { Name =  "Тульская обл", City = tula}
                    };

                foreach (var district in districs)
                {
                    dbContext.Districts.Add(district);
                }

                dbContext.SaveChanges();
            }


            if (!dbContext.Streets.Any())
            {
                #region
//.........这里部分代码省略.........
开发者ID:RR-Studio,项目名称:RealEstateCrm,代码行数:101,代码来源:InitTestData.cs

示例12: CreateAcount

        private async Task CreateAcount(ApplicationDbContext context, UserManager<ApplicationUser> userManager, string name, string surname, string email, string password, Configurations.Role role, Configurations.UserType userType)
        {

            if (context.Consumers.Any(x => x.Email == email) || context.Producers.Any(x => x.Email == email))
                return;
            User user;
            switch(userType)
            {
                case Configurations.UserType.Producer:
                    user = new Producer();
                    break;
                case Configurations.UserType.Consumer:
                    user = new Consumer();
                    break;
                default:
                    user = new Consumer();
                    break;
            }                
            user.Name = name;
            user.Surname = surname;
            user.Email = email;
            user.Avatar = Path.Combine(Configurations.UserAvatarStockagePath, Configurations.DefaultFileName);
            user.RegistrationDate = DateTime.Now;
            user.Enable = true;

            switch (userType)
            {
                case Configurations.UserType.Producer:
                    Producer producer = user as Producer;
                    producer.CompanyName = "La ferme de " + producer.Name;
		    producer.Latitude = 44.7354673;
		    producer.Longitude = 4.601407399999971;
                    context.Producers.Add(producer);
                    break;
                case Configurations.UserType.Consumer:
                    context.Consumers.Add(user as Consumer);
                    break;
                default:
                    context.Consumers.Add(user as Consumer);
                    break;
            }


#region Creating linked application data
            var appUser = new ApplicationUser { UserName = user.Email, Email = user.Email };
            appUser.User = user;

            var result = await userManager.CreateAsync(appUser, password);
            if (result.Succeeded)
            {
                //Add user role
                result = await userManager.AddToRoleAsync(appUser, role.ToString());
                //Add user type
                result = await userManager.AddToRoleAsync(appUser, userType.ToString());
            }
#endregion Creating linked application data

            context.SaveChanges();

        }
开发者ID:ChavFDG,项目名称:Old-Stolons,代码行数:60,代码来源:Startup.cs

示例13: Seed

        private async Task Seed(IUnitOfWork uow  , UserManager<ApplicationUser> usrMan, RoleManager<IdentityRole> _RoleManager)
        {

            var email = "[email protected]";
            var RoleName = "CustomerAdmin";
            var role = await _RoleManager.FindByNameAsync(RoleName);
            if (role == null)
            {
                role = new IdentityRole { Name = RoleName };
                await _RoleManager.CreateAsync(role);
            }

        RoleName = "superadmin";
            role = await _RoleManager.FindByNameAsync( RoleName );
            if ( role == null)
            {
                role = new IdentityRole { Name = "SuperAdmin" };
                await _RoleManager.CreateAsync(role);
            }
            
            var appUser = await usrMan.FindByEmailAsync(email);
            if (appUser != null)
            {
                var result = await usrMan.DeleteAsync(appUser);
            }
            else 
            {
                appUser = new ApplicationUser() { UserName = email, Email = email };
                var result2 = await usrMan.CreateAsync(appUser, "Shafiro2,");
                if (result2.Succeeded)
                {
                    await usrMan.AddToRoleAsync(appUser,  RoleName ); 
                    var hrmUser = new User()
                    {
                        UserID = "7310209296",
                        FirstName = "Gabriel",
                        LastName = "Tekin",
                        UserName = "gabtek",
                        UserCode = "tekgab",
                        PhoneNumber = "0702385537"
                    };
                    if (uow.UserRepository.GetEagerLoad( w => w.UserID.Equals( hrmUser.UserID, StringComparison.OrdinalIgnoreCase )).FirstOrDefault()   == null )
                    {
                        uow.UserRepository.Insert(hrmUser);
                        uow.Save();
                    }
                    
                }
                else
                {
                    var code = result2.Errors.FirstOrDefault().Code;
                }
            }

            } // method seed 
开发者ID:gomaltao,项目名称:HRM,代码行数:55,代码来源:Startup.cs

示例14: RoleCheckBox_CheckChanged

    protected void RoleCheckBox_CheckChanged(object sender, EventArgs e)
    {
        // Reference the CheckBox that raised this event
        CheckBox RoleCheckBox = sender as CheckBox;

        // Get the currently selected user and role
        string selectedUserName = UserList.SelectedValue;
        var um = new UserManager();
        var user = um.FindByName(selectedUserName);
        string roleName = RoleCheckBox.Text;

        // Determine if we need to add or remove the user from this role
        if (RoleCheckBox.Checked)
        {
            // Add the user to the role
            um.AddToRoleAsync(user.Id, roleName);

            // Display a status message
            ActionStatus.Text = string.Format("User {0} was added to role {1}.", selectedUserName, roleName);
        }
        else
        {
            // Remove the user from the role
            um.RemoveFromRoleAsync(user.Id, roleName);

            // Display a status message
            ActionStatus.Text = string.Format("User {0} was removed from role {1}.", selectedUserName, roleName);
        }

        // Refresh the "by role" interface
        DisplayUsersBelongingToRole();
    }
开发者ID:nkarastamatis,项目名称:HickoryPTASite,代码行数:32,代码来源:UsersAndRoles.aspx.cs

示例15: EditbuildingUserPermission

        /// <summary>
        /// remove all current permission for the given user and insert new given permissions. 
        /// </summary>
        /// <param name="newRoles">Accepts a list of RolesName type string</param>
        /// <param name="UserID">Accepts a 128 chr userID type string</param>
        /// <returns></returns>
        public async Task<string> EditbuildingUserPermission(List<string> newRoles, string UserID)
        {
            var result = "";
            var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            //get all roles for the current user
            List<string> AllRoles = UserManager.GetRoles(UserID).ToList();
            //delete all the roles
            foreach (var item in AllRoles)
            {
                await UserManager.RemoveFromRoleAsync(UserID, item);
            }
            //add new roles 
            foreach (var item in newRoles)
            {
                if (RoleManager.RoleExists(item))
                {
                    await UserManager.AddToRoleAsync(UserID, item);
                }
            }

            return result;

        }
开发者ID:dioscarr,项目名称:PointerSecurityMonitor,代码行数:30,代码来源:RegisterUsers.cs


注:本文中的UserManager.AddToRoleAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。