Identity 2.0用户的UserRole始终为空

时间:2016-07-18 11:28:10

标签: c# asp.net-mvc-5 asp.net-identity roles user-roles

所以我遇到了Identity和UserRoles的问题。我继承了基类,然后添加了一些自定义字段。用户对象现在有一个人,其他两个类继承自(申请人和审阅者)。

我已经尝试过这么多,以便在模型构建器中重新排序表的映射,删除我的自定义继承类,强制延迟加载。

对此有任何建议或帮助将不胜感激。

这是申请人的背景。

dir = getDirectory("the directory with all your files");
files = getFileList(dir);
out = getDirectory ("Select output directory");
number = lengthOf(files); // normally 12 in your case
i=0;
while (i < number) {
    // write a function to extract the x and y coordinates, the width and the height of each rectangle of your grid. For that, you have to understand the code of grid.java to understand how you can have the coordinates of each rectangle.
    listcoordinates = yourfunction(files[i], 2923779);// return a vector of (x0, y0, width0, height0, x1, y1, etc...) => x= x coordinate on the top left of the square, y= y coordinate on the top left of the square
    for(j=0; j<lengthOf(listcoordinates); j+4) //foreach coordinate that you extract
     {
        makeRectangle(listcoordinates[j], listcoordinates[j+1], listcoordinates[j+2], listcoordinates[j+3]);
        run("Duplicate...", "title=blabla"+ i + j +".tif");
        saveAs("Tiff", out+ "blabla" + i + j + ".tif");
     }
}
  

Db Initialiser。事情的数据库方面似乎都很好,但什么时候   我登录系统,登录成功,但是当它   重定向到主页控制器索引,索引页面使用   [授权(Roles =“Reviewer”)],这就是失败的地方。它说   user不在该角色中,但在数据库中UserId已配对   使用UserRoles表中的RoleID。因此,用户的角色是   空。

 public class ApplicantContext : IdentityDbContext<User>
        {
            public ApplicantContext()
                : base("ApplicantDbConnection")
            {
                this.Configuration.LazyLoadingEnabled = true;
            }


            public DbSet<Person> People { get; set; }
            public DbSet<Applicant> Graduates { get; set; }
            public DbSet<Reviewer> Reviewers { get; set; }



            //stop pluralising generated tables
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);

                modelBuilder.Entity<User>().ToTable("Users");
                modelBuilder.Entity<Role>().HasKey<string>(r => r.Id).ToTable("Roles");
                modelBuilder.Entity<User>().HasRequired(i => i.Person).WithMany().HasForeignKey<int>(i => i.PersonID);
                modelBuilder.Entity<User>().HasMany<UserRole>((User u) => u.UserRoles);
                modelBuilder.Entity<UserRole>().HasKey(r => new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("UserRoles");

                modelBuilder.Entity<IdentityUser>()
                   .ToTable("Users");

                modelBuilder.Entity<IdentityRole>()
                    .ToTable("Roles");

                modelBuilder.Entity<IdentityUserRole>()
                    .ToTable("UserRoles");

                modelBuilder.Entity<IdentityUserClaim>()
                    .ToTable("UserClaims");

                modelBuilder.Entity<IdentityUserLogin>()
                    .ToTable("UserLogins");



            }
        }

继承自IdentityRole的自定义角色类。

public class DataInitialiser : CreateDatabaseIfNotExists<ApplicantContext>
    {

        protected override void Seed(ApplicantContext context)
        {

            var manager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            manager.Create(new IdentityRole("Reviewer"));
            manager.Create(new IdentityRole("Applicant"));

            ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<User>(context));
            User user = new User
            {
                Person = new Reviewer
                {

                    FirstName = "Grant",
                    MiddleNames = "Mark",
                    Surname = "Weatherston",
                    OfficeID = 1,
                },
                Email = "test@test.com",
                UserName = "test@test.com",
                PhoneNumber = "0123456789",
            };

            userManager.Create(user, "Password123");
            userManager.AddToRole(user.Id, "Reviewer");

            context.SaveChanges();

            base.Seed(context);
        }

    }

自定义用户类继承自身份用户并添加属性Person。

 public class Role : IdentityRole
    {
        public Role() { }
        public Role(string name) :base(name)
        {
        }

    }

自定义用户角色类。

 public class User : IdentityUser
    {
        public User() { }

        public int PersonID { get; set; }

        [ForeignKey("PersonID")]
        public virtual Person Person { get; set; }

        public virtual ICollection<UserRole> UserRoles {get;set;}

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

自定义角色管理器。

    public class UserRole : IdentityUserRole
        {

        }

自定义UserManager

public class ApplicationRoleManager : RoleManager<IdentityRole>
    {

        public ApplicationRoleManager(RoleStore<IdentityRole> roleStore)
            : base(roleStore)
        {

        }

    }

1 个答案:

答案 0 :(得分:0)

这有点过了,但我通过在userIdentity声明之前添加以下行解决了这个问题:

await manager.UpdateSecurityStampAsync(this.Id);

其中managerUserManager

的实例

这会使用当前用户的ID重置安全标记。