198

Got the following ProviderException :

The Role Manager feature has not been enabled.

So far so good.

Is there somewhere a method that can be called to check if the Role Manager has been enabled or not?

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
gsharp
  • 27,557
  • 22
  • 88
  • 134

7 Answers7

306

You can do this by reading from the boolean property at:

System.Web.Security.Roles.Enabled

This is a direct read from the enabled attribute of the roleManager element in the web.config:

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


Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx

Infotekka
  • 10,307
  • 2
  • 20
  • 17
  • 1
    how can I do this from code instead of `web.config`? I tried putting it in `Application_Start` and it says `This method can only be called during the application's pre-start initialization phase.` – Maslow May 08 '13 at 15:17
  • 1
    Where does this go in web.config? – Matt Connolly Jun 03 '13 at 07:10
  • 22
    After adding above to web.config `roleManager` is enabled. But now I am getting exception `Unable to connect to SQL Server database` – Irfan Y Jan 04 '16 at 13:51
  • 2
    @Infotekka "Unable to connect to SQL Server database" error. – Jack Apr 04 '16 at 14:10
  • 1
    The `Unable to connect to SQL Server database` error is likely because once you have enabled the role manager, your application is attempting to use the default AspNetSqlRoleProvider that is configured in your machine.config. You will need to configure your own role provider and add the configuration elements to the `roleManager` block in your web.config. – Infotekka Nov 22 '16 at 17:32
  • Apparently this only works with IIS? How do I enable this in local developer mode? I'm not ready to port this app over to IIS yet. – Nathan McKaskle Jan 18 '17 at 20:39
  • 2
    wow, this is a great answer, I don't even have to config anything, just works like a charm. Once configured in web.config, I can just check User.Identity.IsAuthenticated to see if a login user is authenticated. So cool asp.net – Quan Mar 11 '17 at 05:22
53

If you got here because you're using the new ASP.NET Identity UserManager, what you're actually looking for is the RoleManager:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

roleManager will give you access to see if the role exists, create, etc, plus it is created for the UserManager

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
  • 74
    What does the 3 year old have to do with anything? I got taken to this post from Google because I was dealing with an issue setting up Identity. Since I figured it out...the next person dealing with the same issue as me who gets brought here by Google will know what to do... – Serj Sagan Apr 23 '14 at 20:23
  • 2
    Also, the Identity UserManager has a useful feature to get roles for the given user: UserManager.GetRolesAsync(User.Identity.GetUserId()); – keithl8041 Nov 17 '15 at 22:59
  • Where do you put var roleManager = new RoleManager(new RoleStore(new ApplicationDbContext())); ? – Mario Mar 19 '17 at 18:35
  • You can do it anywhere in the app. You'll obviously need to resolve some references, but anywhere you need roles in an Identity app, you can use this statement. – Serj Sagan Mar 19 '17 at 22:24
11

I found 2 suggestions elsewhere via Google that suggested a) making sure your db connectionstring (the one that Roles is using) is correct and that the key to it is spelled correctly, and b) that the Enabled flag on RoleManager is set to true. Hope one of those helps. It did for me.

Did you try checking Roles.Enabled? Also, you can check Roles.Providers to see how many providers are available and you can check the Roles.Provider for the default provider. If it is null then there isn't one.

Newclique
  • 494
  • 3
  • 15
  • Thanks for you answer. But it's not what I want. I want a method that check's if the Role Manager feature is enabled or not, without caching the ProviderException for that purpose. – gsharp Oct 12 '10 at 07:52
8

I found this question due the exception mentioned in it. My Web.Config didn't have any <roleManager> tag. I realized that even if I added it (as Infotekka suggested), it ended up in a Database exception. After following the suggestions in the other answers in here, none fully solved the problem.

Since these Web.Config tags can be automatically generated, it felt wrong to solve it by manually adding them. If you are in a similar case, undo all the changes you made to Web.Config and in Visual Studio:

  1. Press Ctrl+Q, type nuget and click on "Manage NuGet Packages";
  2. Press Ctrl+E, type providers and in the list it should show up "Microsoft ASP.NET Universal Providers Core Libraries" and "Microsoft ASP.NET Universal Providers for LocalDB" (both created by Microsoft);
  3. Click on the Install button in both of them and close the NuGet window;
  4. Check your Web.config and now you should have at least one <providers> tag inside Profile, Membership, SessionState tags and also inside the new RoleManager tag, like this:

    <roleManager defaultProvider="DefaultRoleProvider">
        <providers>
           <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=NUMBER" connectionStringName="DefaultConnection" applicationName="/" />
        </providers>
    </roleManager>
    
  5. Add enabled="true" like so:

    <roleManager defaultProvider="DefaultRoleProvider" enabled="true">
    
  6. Press F6 to Build and now it should be OK to proceed to a database update without having that exception:

    1. Press Ctrl+Q, type manager, click on "Package Manager Console";
    2. Type update-database -verbose and the Seed method will run just fine (if you haven't messed elsewhere) and create a few tables in your Database;
    3. Press Ctrl+W+L to open the Server Explorer and you should be able to check in Data Connections > DefaultConnection > Tables the Roles and UsersInRoles tables among the newly created tables!
Community
  • 1
  • 1
CPHPython
  • 12,379
  • 5
  • 59
  • 71
  • 2
    "_Since Web.Config fields are automatically generated_" This is not entirely correct. While many NuGet packages will automatically adjust the config files, there is no set rule requiring them to do so. – Kevin R. Apr 19 '16 at 21:59
  • This is perfect. Thnx – sapatelbaps Feb 05 '19 at 20:23
8

If you are using ASP.NET Identity UserManager you can get it like this as well:

var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

var roles = userManager.GetRoles(User.Identity.GetUserId());

If you have changed key for user from Guid to Int for example use this code:

var roles = userManager.GetRoles(User.Identity.GetUserId<int>());
Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • This worked for me. Please say why if you are voting down. – Ogglas Jul 06 '17 at 07:03
  • this doesnt work becuase you need to cast userid to int such that: userManager.GetRoles(Convert.ToInt32(User.Identity.GetUserId())); – toy Jul 25 '17 at 22:47
  • @toy No, will get the value as int. No need to convert. Of course for this to work Identity key needs to be int. – Ogglas Jul 25 '17 at 23:15
-1
<roleManager
  enabled="true"
  cacheRolesInCookie="false"
  cookieName=".ASPXROLES"
  cookieTimeout="30"
  cookiePath="/"
  cookieRequireSSL="false"
  cookieSlidingExpiration="true"
  cookieProtection="All"
  defaultProvider="AspNetSqlRoleProvider"
  createPersistentCookie="false"
  maxCachedResults="25">
  <providers>
    <clear />
    <add
       connectionStringName="MembershipConnection"
       applicationName="Mvc3"
       name="AspNetSqlRoleProvider"
       type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <add
       applicationName="Mvc3"
       name="AspNetWindowsTokenRoleProvider"
       type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </providers>
</roleManager>
-1

Here is the code that you need to put in your Account Controller in MVC5 and later to get the list of roles of a user:

csharp public async Task<ActionResult> RoleAdd(string UserID) { return View(await UserManager.GetRolesAsync(UserID)).OrderBy(s => s).ToList()); }

There is no need to use Roles.GetRolesForUser() and enable the Role Manager Feature.

Rich Turner
  • 10,800
  • 1
  • 51
  • 68
Uncle Tech
  • 84
  • 5