1

I created a new ASP.NET MVC 5 project in Visual Studio 2013 (Express for Web), and I imported a database, but when I try to validate the user role by using

if(User.IsInRole("Admin"))

it still is identifying the user as a regular user, and not as Admin. I'm wondering how I can get the user roles in a controller after importing the database?

And, how do I make sure that the roles are imported to my ASP.NET MVC application?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
2strange
  • 33
  • 7
  • you need to setup the role manager, see this answer: https://stackoverflow.com/a/39139606/5519026 – LazZiya Oct 17 '17 at 07:02

1 Answers1

0

Make sure you have the necessary data in your database. You got to be sure that the role is in the "AspNetRoles" table and the user is linked in the "AspNetUserRoles" table. To make sure you have data, you can use following seeds:

public static class RoleSeeder
{
    public static void Seed()
    {
        CreateRole("Admin", "Administratie", "Administratie");
        ...
    }

    private static void CreateRole(string name, string description, string group)
    {
        using (var db = new DbContext())
        {
            if (!db.Roles.Any(r => r.Name == name))
            {
                var role = new Role { Name = name, Description = description, Group = group };

                var store = new RoleStore<Role>(db);
                var manager = new RoleManager<Role>(store);

                manager.Create(role);
            }
            else
            {
                var store = new RoleStore<Role>(db);
                var manager = new RoleManager<Role>(store);

                var dbRole = manager.FindByName(name);
                dbRole.Description = description;
                dbRole.Group = group;

                manager.Update(dbRole);
            }
        }
    }
}

No reason to write your own role manager.

Jelle Oosterbosch
  • 1,731
  • 15
  • 17