Using UserManager and RoleManager in Microsoft.AspNet.Identity;

I have used this before, and I cannot let life in me show what is going wrong.

@using System.Data.Entity; @using Microsoft.AspNet.Identity; @using Microsoft.AspNet.Identity.EntityFramework; using(ApplicationDbContext db = new ApplicationDbContext()) { var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = User.Identity.GetUserId(); if(user != null) { string role = "Admin"; if (!rm.RoleExists(role)) { var roleResult = rm.Create(new IdentityRole(role)); if (!roleResult.Succeeded) { //error stuff }; } if (!um.IsInRole(user, role)) { um.AddToRole(user, role); } } } 

When I run this, I skip the role creation element (because I already added this to the database), but when it falls into the user bit "administrator role", the line is um.AddToRole (user, role), but then I get a message about error stating that I have a violation because I am trying to duplicate a key.

I don’t understand why the program says when debugging: “There is no user with this name who has the Admin role,” and later, when he tries to add this role, I’m presented with “Hello, this user already has the administrator role, and you cannot add it again "

Before, when I used RoleProviders, I had to change my web.config and add information there, but I didn’t, because I don’t need to !?

This is probably very simple, but I'm stuck.

Just for clarity, how to check if a registered user belongs to the Admin role with AspNet.Identity.

Yours faithfully

+6
source share
1 answer

Ok, so the problem is that turning the distracting load causes this problem. I upgraded Microsoft Identity to 2.0, but still not happy. Apparently, this is a known mistake that they are addressing.

Not perfect, as I always lazily lose. This is not a massive application, so performance is not a problem. Just so everyone knows.

+2
source

All Articles