Ajouter le rôle dans ASP. Identité NET

Mots clés : asp.netasp.net-identityasp.net

meilleur 4 Réponses Ajouter le rôle dans ASP. Identité NET

vote vote

99

RoleManager = new RoleManager<IdentityRole>(                   new RoleStore<IdentityRole>(new MyDbContext())); var roleresult = RoleManager.Create(new IdentityRole(roleName)); 
vote vote

82

var um = new UserManager(); um.AddClaimAsync(1, new Claim(ClaimTypes.Role, "administrator")); 
vote vote

74

   UserManager userManager = new UserManager();     var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());     var roleManager = new RoleManager<IdentityRole>(roleStore);     var applicationRoleAdministrator = new IdentityRole("superadmin");     if (!roleManager.RoleExists(applicationRoleAdministrator.Name))     {         roleManager.Create(applicationRoleAdministrator);     }      ApplicationUser applicationUserAdministrator = userManager.FindByName(User.Identity.Name);      if (!userManager.GetRoles(applicationUserAdministrator.Id).Contains("superadmin"))     {         Response.Redirect("~/account/login.aspx?ReturnUrl=" + Request.Url.AbsolutePath);     } 
 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>     {         public ApplicationDbContext()             : base("DefaultConnection")         {         }     } 
public class ApplicationRoleManager : RoleManager<IdentityRole> {     public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)         : base(roleStore)     {     }      public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)     {         //return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));         return new ApplicationRoleManager(new RoleStore<IdentityRole>(new ApplicationDbContext()));     } } 
  app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 
private ApplicationRoleManager _roleManager;  public ApplicationRoleManager RoleManager {     get     {         return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();     }     private set     {         _roleManager = value;     } } 
vote vote

68

HttpContext.Current.User.IsInRole("some role") 

Questions similaires