• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# IdentityRole类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中IdentityRole的典型用法代码示例。如果您正苦于以下问题:C# IdentityRole类的具体用法?C# IdentityRole怎么用?C# IdentityRole使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



IdentityRole类属于命名空间,在下文中一共展示了IdentityRole类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: RegisterUser

        public async Task<IdentityResult> RegisterUser(UserModel userModel, string roleName)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = userModel.UserName,
                Email = userModel.UserName
            };

            var result = await _userManager.CreateAsync(user, userModel.Password);

            if (result == IdentityResult.Success)
            {
                var role = await _roleManager.FindByNameAsync(roleName);
                if (role == null)
                {
                    role = new IdentityRole(roleName);
                    var roleresult = await _roleManager.CreateAsync(role);
                }

                var userFromDb = await _userManager.FindByNameAsync(user.UserName);

                if (userFromDb != null)
                {
                    await _userManager.AddToRoleAsync(userFromDb.Id, roleName);
                }
            }

            return result;
        }
开发者ID:lachezar1990,项目名称:test8,代码行数:29,代码来源:AuthRepository.cs


示例2: Insert

 /// <summary>
 /// Inserts a new Role in the Roles table
 /// </summary>
 /// <param name="roleName">The role's name</param>
 /// <returns></returns>
 public int Insert(IdentityRole role)
 {
     using (var db = _database.Open())
     {
         return (int)db.Insert<IdentityRole>(role);
     }
 }
开发者ID:jamesmaxwell,项目名称:AspNet.Identity.ServiceStack,代码行数:12,代码来源:RoleTable.cs


示例3: IdentityRoleSet_Id

        public void IdentityRoleSet_Id()
        {
            var role = new IdentityRole();
            role.Id = Guid.NewGuid().ToString();

            role.Id = null;
        }
开发者ID:thermous,项目名称:identitydocumentdb,代码行数:7,代码来源:IdentityRoleTests.cs


示例4: Page_Load

        protected void Page_Load(object sender, EventArgs e) {
            Feedback.Visible = false;
            
            Guid roleId;
            if (!Request.QueryString["id"].TryParseGuid(out roleId)) {
                ShowError(Feedback, "The parameter for id is not in the correct format!");
                SaveButton.Visible = false;
                FormFields.Visible = false;
                return;
            }

            _roleManager = IdentityRoleManager.GetManager();
            _role = _roleManager.FindById(roleId);

            if (_role == null) {
                ShowError(Feedback, "No role was found for the given id!");
                SaveButton.Visible = false;
                FormFields.Visible = false;
                return;
            }

            SaveButton.Click += SaveButton_Click;

            if (!IsPostBack) {
                RoleId.Value = roleId.ToString();
                RoleName.Text = _role.Name;

                if (Request.QueryString["message"] == "created") {
                    ShowMessage(Feedback, "Role has been created!");
                }
            }

            RenderUsersInRole();
        }
开发者ID:KalikoCMS,项目名称:KalikoCMS.Core,代码行数:34,代码来源:EditRole.aspx.cs


示例5: Delete

        public JsonResult Delete(IdentityRole role)
        {
            _context.Entry(role).State = EntityState.Deleted;
            _context.SaveChanges();

            return Json(_context.Roles.ToList(), JsonRequestBehavior.AllowGet);
        }
开发者ID:fabiopsouza,项目名称:Learning.AspNetMVC,代码行数:7,代码来源:RolesController.cs


示例6: Create

        public JsonResult Create(IdentityRole role)
        {
            _context.Roles.Add(role);
            _context.SaveChanges();

            return Json(_context.Roles.ToList(), JsonRequestBehavior.AllowGet);
        }
开发者ID:fabiopsouza,项目名称:Learning.AspNetMVC,代码行数:7,代码来源:RolesController.cs


示例7: RegisterCustomerAsync

        public async Task<IdentityResult> RegisterCustomerAsync(UserModel userModel, AppRole appRole = AppRole.customer)
        {
            var addToRoleResult = new IdentityResult();
            // Add generate username to the model
            IdentityUser user = new IdentityUser
            {
                UserName = userModel.UserName,
                Email = userModel.EmailAddress,
                EmailConfirmed = true,
                PhoneNumber = userModel.PhoneNumber,
                PhoneNumberConfirmed = true,
            };

            var result = await _userManager.CreateAsync(user, userModel.Password);

            //Role-user combination is managed as Contact-Role combination in ContactRole table
            //Create Role Admin if it does not exist
            var _role = await _roleManager.FindByNameAsync(appRole.ToString());
            if (_role == null)
            {
                _role = new IdentityRole(appRole.ToString());
                var roleresult = await _roleManager.CreateAsync(_role);
            }
            var rolesForUser = await _userManager.GetRolesAsync(user.Id);
            if (!rolesForUser.Contains(_role.Name))
            {
                addToRoleResult = await _userManager.AddToRoleAsync(user.Id, _role.Name);
            }

            return addToRoleResult;
        }
开发者ID:itssourabh22,项目名称:projectIGI,代码行数:31,代码来源:AuthRepository.cs


示例8: RoleViewModel

 public RoleViewModel(IdentityRole role)
 {
     this.Id = role.Id;
     this.Name = role.Name;
     this.ConcurrencyStamp = role.ConcurrencyStamp;
     //this.Description = role.Description;
 }
开发者ID:RiteshPahwa,项目名称:AspNetBlog,代码行数:7,代码来源:IdentityViewModels.cs


示例9: GetRolesForUserShouldRetrieveCorrectRoles

        public void GetRolesForUserShouldRetrieveCorrectRoles()
        {
            var role1 = new IdentityRole(GetNewRandomName());
            var role2 = new IdentityRole(GetNewRandomName());

            _roleManager.Create<IdentityRole>(role1);
            _roleManager.Create<IdentityRole>(role2);

            var user1 = new IdentityUser(GetNewRandomName());
            var user2 = new IdentityUser(GetNewRandomName());
            var user3 = new IdentityUser(GetNewRandomName());

            _userManager.Create(user1, _password);
            _userManager.Create(user2, _password);
            _userManager.Create(user3, _password);
            _userManager.AddToRole(user1.Id, role1.Name);
            _userManager.AddToRole(user1.Id, role2.Name);
            _userManager.AddToRole(user2.Id, role1.Name);
            _userManager.AddToRole(user3.Id, role2.Name);

            var user1RoleNames = _userManager.GetRoles(user1.Id);
            var user2RoleNames = _userManager.GetRoles(user2.Id);
            var user3RoleNames = _userManager.GetRoles(user3.Id);

            Assert.AreEqual(2, user1RoleNames.Count);
            Assert.AreEqual(1, user2RoleNames.Count);
            Assert.AreEqual(1, user3RoleNames.Count);

            Assert.IsTrue(user1RoleNames.Any(r => r == role1.Name));
            Assert.IsTrue(user1RoleNames.Any(r => r == role2.Name));
            Assert.IsTrue(user2RoleNames.Any(r => r == role1.Name));
            Assert.IsTrue(user3RoleNames.Any(r => r == role2.Name));
        }
开发者ID:edulon,项目名称:AspNet.Identity.OracleProvider,代码行数:33,代码来源:RoleManagerTests.cs


示例10: Add

        public ActionResult Add(IdentityRole model)
        {
            try
            {
                db.Roles.Add(model);
                db.SaveChanges();
                var Projectdb = new ProjectMvcDbContext();
                foreach (var p in Projectdb.WebActions)
                {
                    var perm = new Permission
                    {
                        Allow = false,
                        RoleId = model.Id,
                        WebActionId = p.Id
                    };
                    Projectdb.Permissions.Add(perm);
                }

                Projectdb.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception Ex)
            {
                ModelState.AddModelError("", Ex.Message);
                ViewBag.Role = db.Roles;
                return View("Index", model);
            }
        }
开发者ID:SamYao779,项目名称:DemoCodeProjectMVC5,代码行数:28,代码来源:RoleController.cs


示例11: SeedAdmin

        internal static void SeedAdmin(HotelSystemDbContext context)
        {
            const string adminEmail = "[email protected]";
            const string adminPassword = "adminadmin";

            if (context.Users.Any(u => u.Email == adminEmail))
            {
                return;
            }

            var admin = new User()
            {
                Email = adminEmail,
                UserName = adminEmail,
                PasswordHash = new PasswordHasher().HashPassword(adminPassword),
                FirstName = "Admin",
                LastName = "Admin",
                BirthDate = new DateTime(1950, 2, 20),
                PhoneNumber = "0888888888888",
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var adminRole = new IdentityRole { Name = GlobalConstants.AdministratorRole, Id = Guid.NewGuid().ToString() };
            context.Roles.AddOrUpdate(adminRole);

            admin.Roles.Add(new IdentityUserRole { RoleId = adminRole.Id, UserId = admin.Id });
            context.Users.Add(admin);
            context.SaveChanges();
        }
开发者ID:iwelina-popova,项目名称:HotelSystem,代码行数:29,代码来源:DataSeeder.cs


示例12: Create

 public ActionResult Create(IdentityRole Role)
 {
     
     context.Roles.Add(Role);
     context.SaveChanges();
     return RedirectToAction("Index");
 }
开发者ID:Eder-Montoya,项目名称:one,代码行数:7,代码来源:RoleController.cs


示例13: Insert

        public JsonData Insert(IdentityRole entity, string userId)
        {
            try
            {
                using (var db = new DataContext())
                {
                    if (entity == null) throw new ArgumentNullException("The new" + " record is null");

                    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

                    //Create Roles if they do not exist
                    if (!roleManager.RoleExists(entity.Name))
                    {
                        roleManager.Create(new IdentityRole(entity.Name));
                    }
                    db.SaveChanges();

                    return DataHelpers.ReturnJsonData(entity, true, "Saved successfully", 1);
                }
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
开发者ID:biggash730,项目名称:SemanticUI_Knockout_ASPMVC_Starter,代码行数:25,代码来源:RoleRepo.cs


示例14: CreateAdminUser

        private async Task CreateAdminUser()
        {
          var username = "admin";//ConfigurationManager.AppSettings["DefaultAdminUsername"];
          var password = "password123";//ConfigurationManager.AppSettings["DefaultAdminPassword"];

          using (var context = new ApplicationDbContext())
          {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

            var role = new IdentityRole(RoleName);

            var result = await roleManager.RoleExistsAsync(RoleName);
            if (!result)
            {
              await roleManager.CreateAsync(role);
            }

            var user = await userManager.FindByNameAsync(username);
            if (user == null)
            {
              user = new ApplicationUser { UserName = username, Email = "[email protected]", First = "Big", Last="Admin Person" };
              await userManager.CreateAsync(user, password);
              await userManager.AddToRoleAsync(user.Id, RoleName);
            }
          }
        }
开发者ID:humayuns,项目名称:ember-user-admin,代码行数:27,代码来源:Startup.Auth.cs


示例15: AddRoleToUser

        public void AddRoleToUser(string userName, string roleName)
        {
            var role = this.roles.All()
                .FirstOrDefault(r => r.Name == roleName);

            if (role == null)
            {
                role = new IdentityRole
                {
                    Name = roleName
                };

                this.roles.Add(role);
                this.roles.SaveChanges();
            }

            var user = this.users.All().FirstOrDefault(u => u.UserName == userName);

            var userRole = this.userRoles.All()
                .FirstOrDefault(r => r.UserId == user.Id && r.RoleId == role.Id);

            if (userRole == null)
            {
                user.Roles.Add(new IdentityUserRole
                {
                    UserId = user.Id,
                    RoleId = role.Id
                });

                this.users.Update(user);

                this.users.SaveChanges();
            }
        }
开发者ID:TsvetanMilanov,项目名称:Employer-Employee-Hunt,代码行数:34,代码来源:RolesService.cs


示例16: Application_Start

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Tạo role sẵn
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

            List<string> roleNameList = new List<string> { "Admin"
                                                         , "Designer"
                                                         , "Mod"
                                                         , "Uploader"
                                                         , "Subteam"
                                                         , "Subber"
                                                         , "VIP"
                                                         , "Member" };
            foreach (string roleName in roleNameList)
            {
                if (!roleManager.RoleExists(roleName))
                {
                    var newRole = new IdentityRole();
                    newRole.Name = roleName;
                    roleManager.Create(newRole);
                }
            }
        }
开发者ID:taihdse60630,项目名称:a4s,代码行数:28,代码来源:Global.asax.cs


示例17: Editar

 public async Task<IActionResult> Editar(IdentityRole role)
 {
     var r = await _roleManager.FindByIdAsync(role.Id);
     r.Name = role.Name;
     await _roleManager.UpdateAsync(r);
     return Redirect();
 }
开发者ID:hjgraca,项目名称:HelpDeskVNext,代码行数:7,代码来源:AcessosController.cs


示例18: Users

        public ActionResult Users()
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
            if (!roleManager.RoleExists("user"))
            {
                var nRole = new IdentityRole("user");
                roleManager.Create(nRole);
            }
            if (!roleManager.RoleExists("admin"))
            {
                var nRole = new IdentityRole("admin");
                roleManager.Create(nRole);
            }
            if (!roleManager.RoleExists("moderator"))
            {
                var nRole = new IdentityRole("moderator");
                roleManager.Create(nRole);
            }
            if (!roleManager.RoleExists("journalist"))
            {
                var nRole = new IdentityRole("journalist");
                roleManager.Create(nRole);
            }

            var vm = new AdminUsersViewModel();

            vm.Users = db.Users.OrderBy(x => x.UserName).ToList();
            vm.Roles = db.Roles.ToList();

            return View(vm);
        }
开发者ID:mjdean1994,项目名称:Athenaeum,代码行数:31,代码来源:AdminController.cs


示例19: Up

        public override void Up()
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var adminUser = new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(),
                EmailConfirmed = false,
                PhoneNumberConfirmed = false,
                TwoFactorEnabled = false,
                LockoutEnabled = false,
                AccessFailedCount = 0,
                Email = "[email protected]",
                UserName = "[email protected]"
            };

            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);
                var role = new IdentityRole { Name = "Admin" };

                manager.Create(role);
            }

            if (!context.Users.Any(u => u.UserName == "TheGaffer"))
            {
                var store = new UserStore<ApplicationUser>(context);
                var manager = new UserManager<ApplicationUser>(store);

                manager.Create(adminUser, "Seisen1!");
                manager.AddToRole(adminUser.Id, "Admin");
            }
        }
开发者ID:RealHerter,项目名称:TheGaffer,代码行数:34,代码来源:201510021948296_test.cs


示例20: Update

        public JsonData Update(IdentityRole entity, string userId)
        {
            try
            {
                using (var db = new DataContext())
                {
                    if (entity == null) throw new ArgumentNullException("The new" + " record is null");

                    //var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

                    //Update Role Roles if they do not exist
                    var role = db.Roles.FirstOrDefault(x => x.Id == entity.Id);
                    if (role != null)
                    {
                        role.Name = entity.Name;
                        //roleManager.Update(role);
                    }
                    db.SaveChanges();

                    return DataHelpers.ReturnJsonData(entity, true, "Updated successfully", 1);
                }
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
开发者ID:biggash730,项目名称:SemanticUI_Knockout_ASPMVC_Starter,代码行数:27,代码来源:RoleRepo.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IdentityUser类代码示例发布时间:2022-05-24
下一篇:
C# IdentityReference类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap