Assign a user to a role in ASP.NET Identity


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


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.


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

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


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.


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;