Add a role in ASP.NET Identity

Introduction


In order to add a new role in ASP.NET Identity, we use the Create method.

Create


The Create method creates the role passed as a parameter and returns the result of the operation as an IdentityResult object.

IdentityResult result = RoleManager.Create(role);

The Create method is called by the RoleManager, which is responsible for performing the role-related operations.

RoleManager


We use the Get method to get the ApplicationRoleManager from the OwinContext.

private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
    get
    {
        return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); 
    }

    private set
    {
        _roleManager = value;
    }
}

Check the Roles management section, for more information about the configuration of the RoleManager.

Example


[HttpPost]
public ActionResult AddRole(RegisterRoleViewModel model)
{
    if (ModelState.IsValid)
    {
        IdentityRole role = new IdentityRole { Name = model.RoleName};
        IdentityResult result = RoleManager.Create(role);
        if (result.Succeeded)
        {
            string RoleId = role.Id;
            return RedirectToAction("Index", "Home", new { Id = RoleId });
        }

        foreach (string error in result.Errors)
            ModelState.AddModelError("", error);
    }

    return View(model);
}

In the above example, we get the information of the role to create via an HTTP Post request. We instantiate a new IdentityRole object and we pass it as a parameter to the Create method in order to create this new role. We access the Succeeded property of the IdentityResult object to check if the opration was successful. If it is not the case, we loop through the list of Errors and we add them to the ModelState by using the AddModelError method.

The RegisterRoleViewModel object is the ViewModel that we are using in order to render and validate the AddRole view.

public class RegisterRoleViewModel
{
    [Display(Name = "Role name")]
    [Required]
    public string RoleName { get; set; }
}

Namespaces


In order to use the Get method, the Create method, the IdentityResult object, and the IdentityRole object, you have to include the following namespaces :

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