Add User to Role ASP.NET Identity

后端 未结 7 713
梦毁少年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:11

    Check this link: Assigning Roles to Users. You can add a step to your CreateUserWIzard control and choose the roles in that step.

    
        
            
            
            
                

    Choose the role.

    And in the code-behind you will have:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // Reference the SpecifyRolesStep WizardStep 
            WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;
    
            // Reference the RoleList CheckBoxList 
            CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;
    
            // Bind the set of roles to RoleList 
            RoleList.DataSource = Roles.GetAllRoles();
            RoleList.DataBind();
        } 
    }
    protected void RegisterUserWithRoles_ActiveStepChanged(object sender, EventArgs e)
    {
        // Have we JUST reached the Complete step? 
        if (RegisterUserWithRoles.ActiveStep.Title == "Complete")
        {
            // Reference the SpecifyRolesStep WizardStep 
            WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;
    
            // Reference the RoleList CheckBoxList 
            CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;
    
            // Add the checked roles to the just-added user 
            foreach (ListItem li in RoleList.Items)
            {
                if (li.Selected)
                    Roles.AddUserToRole(RegisterUserWithRoles.UserName, li.Text);
            }
        }
    }
    

提交回复
热议问题