How to check role of user by API ? and delete user in role by API ?

thanh phuoc asked on January 1, 2015 13:56

Hi, I want check role name of user by API but i can't and delete user role ?. help me. Thanks.

Correct Answer

thanh phuoc answered on January 1, 2015 14:24

Thanks, I have installed but I do not find the handle to find role in user ?

0 votesVote for this answer Unmark Correct answer

Recent Answers


Brenden Kehren answered on January 1, 2015 14:10

Have you checked the API Examples that are included with your install? You will find the Role management code under /CMSAPIExamples/Code/Administration/Membership/Default.aspx.cs

0 votesVote for this answer Mark as a Correct answer

Brenden Kehren answered on January 1, 2015 15:01

Check if a user is in a role:

UserInfo user = UserInfoProvider.GetUserInfo("MyUserName");
if(user.IsInRole("roleName", "siteName"))
{
    // user is in role specified so do something
}

Straight from API Examples:

/// <summary>
/// Adds a user to a role
/// </summary>
private bool CreateUserRole()
{
    // Get role and user objects
    RoleInfo role = RoleInfoProvider.GetRoleInfo("MyNewRole", SiteContext.CurrentSiteID);
    UserInfo user = UserInfoProvider.GetUserInfo("MyNewUser");

    if ((role != null) && (user != null))
    {
        // Create new user role object
        UserRoleInfo userRole = new UserRoleInfo();

        // Set the properties
        userRole.UserID = user.UserID;
        userRole.RoleID = role.RoleID;

        // Save the user role
        UserRoleInfoProvider.SetUserRoleInfo(userRole);
        return true;
    }
    return false;
}


/// <summary>
/// Removes a user from a role
/// </summary>
private bool DeleteUserRole()
{
    // Get role and user objects
    RoleInfo role = RoleInfoProvider.GetRoleInfo("MyNewRole", SiteContext.CurrentSiteID);
    UserInfo user = UserInfoProvider.GetUserInfo("MyNewUser");

    if ((role != null) && (user != null))
    {
        // Get the user role
        UserRoleInfo deleteRole = UserRoleInfoProvider.GetUserRoleInfo(user.UserID, role.RoleID);

        // Delete the user role
        UserRoleInfoProvider.DeleteUserRoleInfo(deleteRole);
        return true;
    }
    return false;
}
1 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.