1

How is it possible the automatically assign a default role to a registered user. I'm trying this but it is not working and I'm getting the error:

[ProviderException: The role 'Member' was not found.]

This is what I do:

Seed my default role so it exists from the start:

// Configuration.cs, Seed method.

if (!context.Roles.Any(r => r.Name == "Member"))
{
    var store = new RoleStore<IdentityRole>(context);
    var manager = new RoleManager<IdentityRole>(store);
    var role = new IdentityRole { Name = "Member" };

    manager.Create(role); // Member role gets created in AspNetRoles table.
}

Than after update-database, I add a registered user to that role:

// AccountController, Register method (POST).

var user = new ApplicationUser { ... }

if (.. Succeeded)
{
    ..
    if (!Roles.IsUserInRole(user.UserName, "Member"))
        Roles.AddUserToRole(user.UserName, "Member");

    return RedirectToAction("Index", "Home");
}

When registering a new account, I get the error:

[ProviderException: The role 'Member' was not found.] // Member exits in AspNetRoles

Line 176:                    if (!Roles.IsUserInRole(user.UserName, "Member"))
Line 177:                         Roles.AddUserToRole(user.UserName, "Member");
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
user3231419
  • 275
  • 2
  • 7
  • 14

1 Answers1

1

I think you are using the wrong role manager. Roles is very likely the Simple Membership roles provider and not the one from Identity. Try the following:

if (.. Succeeded)
{
    ..
    // if (!await UserManager.IsInRoleAsync(user.Id, "Member"))
    await UserManager.AddToRoleAsync(user.Id, "Member");

    return RedirectToAction("Index", "Home");
}

I commented out the IsInRoleAsync-check as it is not needed IMO if you just created the user.

If not already done, you need to create an async action to use async/await:

public async Task<ActionResult> Register(RegisterModel model)
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
  • Worked like a charm! Is my seeding method also using the wrong role manager or can I leave it like that? – user3231419 Jan 07 '15 at 12:38
  • 1
    @user3231419: No, there you are using `RoleManager` which is the correct one, hence the role showing up in the `AspNetRoles` table and not some `webpages_Roles` table... – Christoph Fink Jan 07 '15 at 12:40
  • Found a little problem with using this method: After I register a new user, the user gets assigned to the "Member"-role in the database but not yet on the _Layout.cshtml page where I check if the active user is a member. It only recognizes that the user has the member-role when I logout and login again, any idea what went wrong? – user3231419 Jan 07 '15 at 17:17
  • @user3231419: See http://stackoverflow.com/questions/20495249/mvc-5-addtorole-requires-logout-before-it-works – Christoph Fink Jan 07 '15 at 17:51