Assign a user to a role in ASP.NET Identity

Introduction


In order to assign a user to a role in ASP.NET Identity, we use the AddToRole method.

AddToRole


The AddToRole method adds a user to a role and returns the result of the operation as an IdentityResult object.

IdentityResult result = UserManager.AddToRole(userId, roleName);

The AddToRole method is called by the UserManager, which is responsible for performing the user-related operations.

UserManager


We use the GetUserManager method to get the ApplicationUserManager from the Owin context.

private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? HttpContext.GetOwinContext().GetUserManager();
    }
    private set
    {
        _userManager = value;
    }
}

Example


private IdentityResult AssignUserToRole(string userId, string roleName)
{
    var result = UserManager.AddToRole(userId, roleName);

    return result;
}

In the above example, we've declared a method that takes two parameters : the id of the user we want to assign and the role name we want to assign the user to. We call the AddToRole method that takes these two params and adds the corresponding user to the given role. We then return the result of the operation.

Namespaces


In order to use the GetUserManager method, the AddToRole method, and the IdentityResult object, you have to include the following namespaces :

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;