with VS 2015 I've created a little MVC App with the default authentification stuff. I've changed nothing but the code in the registration action of the account controller:
var context = new ApplicationDbContext();
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
if (!roleManager.RoleExists("Administrator"))
{
roleManager.Create(new IdentityRole("Administrator"));
}
if (!roleManager.RoleExists("User"))
{
roleManager.Create(new IdentityRole("User"));
}
if (context.Users.Count() == 1)
{
userManager.AddToRole(user.Id, "Administrator");
} else
{
try
{
userManager.AddToRole(user.Id, "User");
}
catch (Exception ex)
{
throw new Exception("Error assigning role: " + ex.Message);
}
}
The first registrated user becomes an "Administrator". Though the "userManager.AddToRole(user.Id, "User");" doesn't throw an exception no following registrated user is assigned to that role (checked the table and also per Authorize(Role...). I can't figure out what's wrong here.