Search code examples
asp.netasp.net-mvcasp.net-identity

unable to add roles in asp.net identity


I was using the following code to add roles of the user.

    Roles.AddUserToRole(model.Email, "COMPANYVIP");

and then i got this error:

    The Role Manager feature has not been enabled

after some research i found out that we have to add the following connection string in web.config

    <configuration>
      <system.web>
        <roleManager enabled="true" />
      </system.web>
    </configuration>

adding this eliminated my first error but now i get this error:

    A network-related or instance-specific error occurred while establishing a connection to SQL Server

what should i do now?


Solution

  • Remove your change in web.config and in Startup.Auth add the following reference to ConfigureAuth:

    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        // Add this reference to RoleManager (without changing any other items)
        // Make sure it is added below ApplicationDbContext.Create
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    }
    

    Then in your Controller, make sure it includes this in the constructor:

    public class YourController : Controller
    {
        // Add this
        private ApplicationRoleManager _roleManager;
    
        // Add roleManager
        public YourController(ApplicationRoleManager roleManager)
        {
            // Add this
            RoleManager = roleManager;
        }
    
        public ApplicationRoleManager RoleManager {
            get {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set {
                _roleManager = value;
            }
        }
    }
    

    and also include this in the Controller's Dispose (if you have it):

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            // include this
            if (_roleManager != null)
            {
                _roleManager.Dispose();
                _roleManager = null;
            }
        }
    
        base.Dispose(disposing);
    }
    

    You may also need to add this code to IdentityConfig (in the App_Start folder if you're using the template):

    public class ApplicationRoleManager : RoleManager<IdentityRole>
    {
        public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
        { }
    
        public static ApplicationRoleManager Create(
            IdentityFactoryOptions<ApplicationRoleManager> options,
            IOwinContext context)
        {
            var manager = new ApplicationRoleManager(
                new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
            return manager;
        }
    }
    

    You should now be able to use the RoleManager in the Controller.