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


C# UserManager.GetRoles方法代码示例

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


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

示例1: Index

        public ActionResult Index()
        {
            var userRoles = new List<RolesViewModel>();
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            //Get all the usernames
            foreach (var user in userStore.Users)
            {
                var r = new RolesViewModel
                {
                    UserName = user.UserName
                };
                userRoles.Add(r);
            }
            //Get all the Roles for our users

            var numberOfDefault = 0;

            foreach (var user in userRoles)
            {
                user.RoleNames = userManager.GetRoles(userStore.Users.First(s => s.UserName == user.UserName).Id);

                if(user.RoleNames.Contains("Default"))
                {
                    numberOfDefault++;
                    TempData["ValidationMessageDefaultUser"] = numberOfDefault + " " + "New User(s) Have Registered";
                    TempData["ValidationMessageIcon"] = "1";
                }
            }

            return View(userRoles);
        }
开发者ID:amoryjh,项目名称:MVC-HPFS,代码行数:33,代码来源:UserController.cs

示例2: isAdminUser

 public Boolean isAdminUser()
 {
     //if user is Authenticated (logged in)
     if (User.Identity.IsAuthenticated)
     {
         //create a variable user with data from the users identity
         var user = User.Identity;
         //create a new instance of the Dbcontext
         ApplicationDbContext context = new ApplicationDbContext();
         //give variable UserManager data from the user
         var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
         //get the role of the current user
         var s = UserManager.GetRoles(user.GetUserId());
         //check to see if the current role is Admin
         if (s[0].ToString() == "Admin")
         {
             //return true;
             ViewBag.admin = true;
         }
         else
         {
             //return false;
             ViewBag.admin = false;
         }
     }
     return false;
 }
开发者ID:DMU-CTEC2902,项目名称:LC-TeamFlash,代码行数:27,代码来源:HomeController.cs

示例3: DeleteRoleForUser

        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
            if (ModelState.IsValid)
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                ViewBag.Token = "2";

                if (userManager.IsInRole(user.Id, RoleName))
                {
                    userManager.RemoveFromRole(user.Id, RoleName);
                    ViewBag.ResultMessage = "Role removed from this user successfully !";
                }
                else
                {
                    ViewBag.ResultMessage = "This user doesn't belong to selected role.";
                }

                // prepopulat roles for the view dropdown
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                ViewBag.Roles = list;

                var userList = context.Users.OrderBy(r => r.Email).ToList().Select(rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();
                ViewBag.userNames = userList;

                ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);
            }

            return View("ManageUserRoles");
        }
开发者ID:dleivas,项目名称:SpecialBreakFast,代码行数:31,代码来源:RolesController.cs

示例4: Search

        public ActionResult Search(string tb_SearchBox)
        {
            List<List<string>> userRoleList = new List<List<string>>();
            if (string.IsNullOrEmpty(tb_SearchBox))
            {
                tb_SearchBox = "";
            }
            var results = (from contact in db.ContactProfiles
                           where
                               contact.FirstName.Contains(tb_SearchBox)
                               || contact.LastName.Contains(tb_SearchBox)
                               || contact.AlternateEmail.Contains(tb_SearchBox)
                               || contact.PrimaryEmail.Contains(tb_SearchBox)
                           select contact).OrderByDescending(m=>m.LastName).ToList();

            foreach (var item in results)
            {

                UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(item.PrimaryEmail, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                List<string>roleList = _userManager.GetRoles(user.Id).ToList();

                userRoleList.Add(roleList);
            }
            userRoleList.Reverse();
            ViewBag.Roles = userRoleList;

            return View("Index", results);
        }
开发者ID:runklem,项目名称:DCC_PortfolioSite,代码行数:29,代码来源:UserListController.cs

示例5: Index

        //Get Index page
        public ActionResult Index()
        {
            var userRoles = new List<RolesViewModel>();
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            //Get all the usernames
            foreach (var user in userStore.Users)
            {
                var r = new RolesViewModel
                {
                    UserName = user.UserName
                };
                userRoles.Add(r);
            }
            //Get all the Roles for our users
            foreach (var user in userRoles)
            {
                user.RoleNames = userManager.GetRoles(userStore.Users.First(s => s.UserName == user.UserName).Id);

                if (user.RoleNames.Contains("Default"))
                {
                    TempData["ValidationMessageIcon"] = "1";
                }
            }

            return View(db.Indices.ToList());
        }
开发者ID:amoryjh,项目名称:MVC-HPFS,代码行数:29,代码来源:HomeController.cs

示例6: ChangeRoleOfUserInGroup

 public ActionResult ChangeRoleOfUserInGroup(string mail)
 {
     //SKapa VM instans
     UserChangeRoleViewModel changeVM = new UserChangeRoleViewModel();
     var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     //Välj en user till Viewmodell
     //ViewBag.Name = changeVM.Name;
     changeVM.Users = repo.ApplicationUsers().Select(u => new SelectListItem
     {
         Text = u.UserName,
         Value = u.Id,
     });
     //ApplicationUser usr = repo.ApplicationUsers().First();
     //Välj vilken av users roll som skall ändras
     //List<IdentityRole> cVM = new List<IdentityRole>();
     changeVM.SelectedUser = repo.ApplicationUsers().Single(m => m.Email == mail).Id;
     changeVM.OldRoles = userManager.GetRoles(changeVM.SelectedUser).Select(o => new SelectListItem
     {
         Text = o,
         Value = o
     });
     //Välj en ny roll till Viewmodell
     changeVM.Roles = repo.RolesList().Select(r => new SelectListItem
     {
         Text = r.Name,
         Value = r.Name
     });
     //Returna View med VM
     return View(changeVM);
 }
开发者ID:jarolex,项目名称:Personalsystem-1,代码行数:31,代码来源:GroupController.cs

示例7: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable<string> userNameHeaderValues = null;
            if (request.Headers.TryGetValues(KawalDesaHeaders.X_KD_USERID, out userNameHeaderValues))
            {
                if (!IsValidEmissRequest(request))
                {
                    var response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not a Valid Request");
                    return Task.FromResult<HttpResponseMessage>(response);
                }

                IEnumerable<String> expireHeaderValues = null;
                if (request.Headers.TryGetValues(KawalDesaHeaders.X_KD_EXPIRES, out expireHeaderValues))
                {
                    if (IsExpiredRequest(expireHeaderValues.FirstOrDefault()))
                    {
                        var response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Your Request Has Expired");
                        return Task.FromResult<HttpResponseMessage>(response);
                    }
                }

                var userName = userNameHeaderValues.First();
                var userManager = new UserManager<User>(new CUserStore<User>(new DB()));
                var user = userManager.FindByName(userName);
                if (user != null)
                {
                    string signature = CryptographyHelper.Sign(request, user.SecretKey);
                    if (signature.Equals(request.Headers.GetValues(KawalDesaHeaders.X_KD_SIGNATURE).FirstOrDefault()))
                    {
                        var identity = new KawalDesaIdentity(user, "Emiss");
                        var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                    }
                }
            }
            else if (HttpContext.Current.Session != null && !String.IsNullOrEmpty((string)HttpContext.Current.Session[KawalDesaController.USERID_KEY]))
            {
                var session = HttpContext.Current.Session;
                var userManager = new UserManager<User>(new CUserStore<User>(new DB()));
                var user = userManager.FindById((string)session[KawalDesaController.USERID_KEY]);
                if (user != null)
                {
                    var identity = new KawalDesaIdentity(user, "Session");
                    var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = principal;
                    }
                }
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:nazhir,项目名称:kawaldesa,代码行数:58,代码来源:AuthorizationHandler.cs

示例8: AddUsertoRole

        public static void AddUsertoRole(UserManager<ApplicationUser> userManager, ApplicationUser user, string roleName)
        {
            var rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(roleName))
            {
                var result = userManager.AddToRole(user.Id, roleName);
            }
        }
开发者ID:rswetnam,项目名称:GoodBoating,代码行数:9,代码来源:SeedServices.cs

示例9: SetupRolesAndUsers

        private static void SetupRolesAndUsers(DbContext context)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            // add roles
            if (!roleManager.RoleExists(Role.Guest.ToString()))
                roleManager.Create(new IdentityRole(Role.Guest.ToString()));
            if (!roleManager.RoleExists(Role.Supplier.ToString()))
                roleManager.Create(new IdentityRole(Role.Supplier.ToString()));
            if (!roleManager.RoleExists(Role.Deactivated.ToString()))
                roleManager.Create(new IdentityRole(Role.Deactivated.ToString()));
            if (!roleManager.RoleExists(Role.User.ToString()))
                roleManager.Create(new IdentityRole(Role.User.ToString()));
            var adminRole = roleManager.FindByName(Role.Admin.ToString());
            if (adminRole == null)
            {
                adminRole = new IdentityRole(Role.Admin.ToString());
                roleManager.Create(adminRole);
            }
            #if DEBUG
            //add admin user
            var admin = userManager.Find(Admin_User, Admin_Pass);
            if (admin == null)
            {
                admin = new ApplicationUser
                {
                    UserName = Admin_User,
                    Email = Admin_Mail,
                    EmailConfirmed = true
                };
                var result = userManager.Create(admin, Admin_Pass);
                // TODO: verify returned IdentityResult
                userManager.AddToRole(admin.Id, Role.Admin.ToString());
                result = userManager.SetLockoutEnabled(admin.Id, false);
            }

            var rolesForUser = userManager.GetRoles(admin.Id);
            if (!rolesForUser.Contains(adminRole.Name))
            {
                var result = userManager.AddToRole(admin.Id, adminRole.Name);
            }

            //add normal user
            if (userManager.Find("[email protected]", "1q2w3e4r") == null)
            {
                var user = new ApplicationUser
                {
                    UserName = "[email protected]",
                    Email = "[email protected]",
                    EmailConfirmed = true
                };
                userManager.Create(user, "1q2w3e4r");
                // TODO: verify returned IdentityResult
                userManager.AddToRole(user.Id, Role.User.ToString());
            }
            #endif
        }
开发者ID:uaandrei,项目名称:d4232ffg,代码行数:57,代码来源:DbConfig.cs

示例10: AssignRole

 public async Task<ActionResult> AssignRole(string username, string rolename)
 {
     UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(_identityDb);
     UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);
     var user = userManager.Users.FirstOrDefault(u => u.UserName == username);
     await Task.Run(() => userManager.RemoveFromRoles(user.Id, userManager.GetRoles(user.Id).ToArray()));
     //var role = roles.FirstOrDefault(r => r == rolename);
     //if(role == null)
     userManager.AddToRole(user.Id, rolename);
     return RedirectToAction("Users", "Admin");
 }
开发者ID:weweboom,项目名称:SE1-Sprint1-Group3,代码行数:11,代码来源:AdminController.cs

示例11: GetUserRolesInfo

		public static List<UserRolesInfo> GetUserRolesInfo(this IQueryable<ApplicationUser> applicationUsers, int count, UserManager<ApplicationUser> userManager)
		{
			return applicationUsers
				.OrderBy(u => u.UserName)
				.Take(count).ToList()
				.Select(user => new UserRolesInfo
				{
					UserId = user.Id,
					UserName = user.UserName,
					UserVisibleName = user.VisibleName,
					Roles = userManager.GetRoles(user.Id).ToList()
				}).ToList();
		}
开发者ID:kontur-edu,项目名称:uLearn,代码行数:13,代码来源:AppUserQueryExtentions.cs

示例12: AssignRole

 public ActionResult AssignRole(AssignRoleViewModel vm)
 {
     using (var context = new ApplicationDbContext())
     {
         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
         var role = _roleRepo.GetById(vm.RoleID);
         manager.AddToRole(vm.UserID, role.Name);
         vm.Roles = manager.GetRoles(vm.UserID);
         vm.User = _repo.GetById(vm.UserID);
     }
     ViewBag.RoleID = new SelectList(_roleRepo.Get(), "Id", "Name", vm.RoleID);
     return View(vm);
 }
开发者ID:vishalavalani,项目名称:Quiz-App,代码行数:13,代码来源:UsersController.cs

示例13: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            using (var db = new DB())
            {
                IEnumerable<string> authorizationHeaderValues = null;
                if (request.Headers.TryGetValues("Authorization", out authorizationHeaderValues))
                {
                    try
                    {
                        var auth = authorizationHeaderValues.First().Split(null)[1];
                        var token = JsonWebToken.Decode(auth, ConfigurationManager.AppSettings["Auth.SecretKey"]);
                        var userManager = new UserManager<User>(new CUserStore<User>(db));
                        var user = userManager.FindById(token.UserId);
                        if (user != null)
                        {
                            var identity = new KawalDesaIdentity(user, "exAuth");
                            var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                            Thread.CurrentPrincipal = principal;
                            if (HttpContext.Current != null)
                            {
                                HttpContext.Current.User = principal;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogManager.GetLogger(typeof(AuthorizationHandler)).Error("Auth error", e);
                    }
                }
                else if (HttpContext.Current.Session != null && !String.IsNullOrEmpty((string)HttpContext.Current.Session[KawalDesaController.USERID_KEY]))
                {
                    var session = HttpContext.Current.Session;
                    var userManager = new UserManager<User>(new CUserStore<User>(db));
                    var user = userManager.FindById((string)session[KawalDesaController.USERID_KEY]);
                    if (user != null)
                    {
                        var identity = new KawalDesaIdentity(user, "Session");
                        var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                    }
                }

                return base.SendAsync(request, cancellationToken);
            }
        }
开发者ID:ekospinach,项目名称:kawaldesa,代码行数:49,代码来源:AuthorizationHandler.cs

示例14: DefaultUser

        public static void DefaultUser(ApplicationDbContext db)
        {

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

            var name = AppConfig.DefaultUser;
            var pwd = AppConfig.DefaultUserPassword;
            const string adminRole = "Admin";
            const string dashboardRole = "Dashboard";
            const string investigateRole = "Investigate";

            //Create Role Admin if it does not exist
            var ar = roleManager.FindByName(adminRole);
            if (ar == null)
            {
                ar = new IdentityRole(adminRole);
                var roleresult = roleManager.Create(ar);
            }

            var dr = roleManager.FindByName(dashboardRole);
            if (dr == null)
            {
                dr = new IdentityRole(dashboardRole);
                var roleresult = roleManager.Create(dr);
            }

            var ir = roleManager.FindByName(investigateRole);
            if (ir == null)
            {
                ir = new IdentityRole(investigateRole);
                var roleresult = roleManager.Create(ir);
            }

            var user = userManager.FindByName(name);
            if (user == null)
            {
                user = new ApplicationUser { UserName = name, Email = name, EmailConfirmed = true };
                var createUser = userManager.Create(user, pwd);
                createUser = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);
            if (!rolesForUser.Contains("Admin"))
            {
                var result = userManager.AddToRole(user.Id, "Admin");
            }
        }
开发者ID:Geekballs,项目名称:Bootmock,代码行数:49,代码来源:Seed.cs

示例15: SelectModuleIndex

        //select available modeule
    
        public ActionResult SelectModuleIndex(string UserID)
        {
            ApplicationDbContext context = new ApplicationDbContext();
            DisplayManagerRoleDelete ObjRole = new DisplayManagerRoleDelete();
            ModuleSelectVM ObjS = new ModuleSelectVM();
            var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
           ObjS.AllRoles = userManager.GetRoles(UserID);

           var LoggedUserID = User.Identity.GetUserId();
           ObjS.BuildingUser = db.BuildingUser.Where(c => c.UserID == LoggedUserID).FirstOrDefault();


           return View(ObjS);
        }
开发者ID:dioscarr,项目名称:PointerSecurityMonitor,代码行数:17,代码来源:ModuleController.cs


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