将新用户和角色添加到asp.net身份示例中

本文关键字:net asp 身份 添加 角色 新用户 用户 | 更新日期: 2023-09-27 18:21:15

我已经安装了asp.net标识示例https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples并尝试与用户一起创建新角色"SAdmin"Sadmin@example.com".用户已创建,但"Sadmin"获得与"Admin"相同的角色

我已将IdentityConfig.cs修改为

    //Create User=Admin@Admin.com with password=Admin@123456 in the Admin role        
    public static void InitializeIdentityForEF(ApplicationDbContext db) {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
        const string name = "admin@example.com";
        const string password = "Admin@123456";
        const string roleName = "Admin";
        const string Sname = "Sadmin@example.com";
        const string Spassword = "SAdmin@123456";
        const string SroleName = "SAdmin";
        //Create Super if it does not exist
        var Srole = roleManager.FindByName(SroleName);
        if (Srole == null)
        {
            Srole = new IdentityRole(roleName);
            var roleresult = roleManager.Create(Srole);
        }
        var Suser = userManager.FindByName(Sname);
        if (Suser == null)
        {
            Suser = new ApplicationUser { UserName = Sname, Email = Sname };
            var result = userManager.Create(Suser, Spassword);
            result = userManager.SetLockoutEnabled(Suser.Id, false);
        }
        // Add Suser to Role Admin if not already added
        var SrolesForUser = userManager.GetRoles(Suser.Id);
        if (!SrolesForUser.Contains(Srole.Name))
        {
            var result = userManager.AddToRole(Suser.Id, Srole.Name);
        }
        //Create Role Admin if it does not exist
        var role = roleManager.FindByName(roleName);
        if (role == null) {
            role = new IdentityRole(roleName);
            var roleresult = roleManager.Create(role);
        }
        var user = userManager.FindByName(name);
        if (user == null) {
            user = new ApplicationUser { UserName = name, Email = name };
            var result = userManager.Create(user, password);
            result = userManager.SetLockoutEnabled(user.Id, false);
        }
        // Add user admin to Role Admin if not already added
        var rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name)) {
            var result = userManager.AddToRole(user.Id, role.Name);
        }
    }

将新用户和角色添加到asp.net身份示例中

问题出在代码中。。。以下代码块负责

    if (Srole == null)
    {
    **Srole = new IdentityRole(roleName);**
    var roleresult = roleManager.Create(Srole);
    }

将突出显示的行更改为

    **Srole = new IdentityRole(SroleName);**

这应该可以解决