Add User to Role ASP.NET Identity

后端 未结 7 710
梦毁少年i
梦毁少年i 2020-12-07 16:47

I know the new Membership includes a \"Simple Role Provider.\"

I can\'t find any help related to creating a user and assigning a role when the user is created. I\'v

7条回答
  •  心在旅途
    2020-12-07 17:30

    I had the same challenge. This is the solution I found to add users to roles.

    internal class Security
    {
        ApplicationDbContext context = new ApplicationDbContext();
    
        internal void AddUserToRole(string userName, string roleName)
        {
            var UserManager = new UserManager(new UserStore(context));
    
            try
            {
                var user = UserManager.FindByName(userName);
                UserManager.AddToRole(user.Id, roleName);
                context.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
    }
    

提交回复
热议问题