Identity 2.0 Пользователь UserRole всегда Null

0 rugbylad_28 [2016-07-18 14:28:00]

Поэтому у меня проблемы с Identity и UserRoles. Я унаследовал от базовых классов, а затем добавил некоторые настраиваемые поля. Пользовательский объект теперь имеет человека, которому наследуются два других класса (Заявитель и Рецензент).

Я пробовал так много, чтобы получить эту работу с точки зрения переупорядочения сопоставлений таблиц в построителе моделей, удаления моих пользовательских унаследованных классов, заставляя ленивую загрузку.

Любые предложения или помощь по этому поводу будут очень признательны.

Это контекст заявителя.

 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");



            }
        }

Db Initialiser. С точки зрения базы данных все кажется прекрасным, но когда я вхожу в систему, логин успешно завершен, однако когда он перенаправляется на индекс Home controller, на странице Index используется [Authorize (Roles = "Reviewer")], и это где выходит из строя. Он говорит, что пользователь не входит в эту роль, однако в базе данных UserId сопряжен с идентификатором RoleID в таблице UserRoles. Поэтому роль пользователя равна нулю.

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 = "[email protected]",
                UserName = "[email protected]",
                PhoneNumber = "0123456789",
            };

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

            context.SaveChanges();

            base.Seed(context);
        }

    }

Пользовательский класс ролей, наследующий от IdentityRole.

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

    }

Пользовательский класс пользователя наследует от пользователя с добавлением свойства Person.

 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
        {

        }

Пользовательский менеджер ролей.

public class ApplicationRoleManager : RoleManager<IdentityRole>
    {

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

        }

    }

Пользовательский UserManager

public class ApplicationUserManager : UserManager<User>
    {
        public ApplicationUserManager(IUserStore<User> store)
            : base(store)
        {
        }

   }

c# asp.net-mvc-5 asp.net-identity roles user-roles


1 ответ


0 Ali Prasla [2017-04-23 01:50:00]

Это немного по причине, но я решил эту проблему, добавив следующую строку непосредственно перед объявлением userIdentity:

await manager.UpdateSecurityStampAsync(this.Id);

Где manager является экземпляром UserManager

Это приведет к сбросу штампа безопасности с помощью текущего идентификатора пользователя.