C# 用户角色/授权不';不能在ASP.NET身份中工作

C# 用户角色/授权不';不能在ASP.NET身份中工作,c#,asp.net-mvc,asp.net-mvc-5,asp.net-identity,asp.net-authorization,C#,Asp.net Mvc,Asp.net Mvc 5,Asp.net Identity,Asp.net Authorization,在我们的DbContext.cs上有这个(模型生成器)代码 base.OnModelCreating(modelBuilder); modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId); modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id); modelBuilder.En

在我们的DbContext.cs上有这个(模型生成器)代码

 base.OnModelCreating(modelBuilder);
 modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
 modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
 modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
 modelBuilder.Entity<ApplicationUser>().ToTable("ApplicationUser");
base.OnModelCreating(modelBuilder);
modelBuilder.Entity().HasKey(l=>l.UserId);
modelBuilder.Entity().HasKey(r=>r.Id);
modelBuilder.Entity().HasKey(r=>new{r.RoleId,r.UserId});
modelBuilder.Entity().ToTable(“ApplicationUser”);
除了授权/用户角色之外,一切正常

检查完所有表后,我注意到IdentityUserRoles表创建了4列:RoleId、UserId、IdentityRole\u Id和ApplicationUser\u Id。

我发现,IdentityRole\u Id和ApplicationUser\u Id[外键]被映射或使用,而不是RoleId和UserId[主键]。不幸的是,标识(Id)数据被插入RoleId/UserId列,默认情况下,IdenityRole_Id/ApplicationUser_Id为NULL

请帮忙

我的代码:

public class RqDbContext : DbContext
{
    private const string ConnectionString = "RqDbContext";

    public RqDbContext() : base(ConnectionString)
    {
    }
    public static RqDbContext Create()
    {
        return new RqDbContext();
    }


    // ----------------------------------------------------------------------
    // Data Tables
    // ----------------------------------------------------------------------

    public DbSet<Quote> Quotes { get; set; }

    public DbSet<Booking> Bookings { get; set; }

    public DbSet<CompanyAccount> CompanyAccounts { get; set; }

    // ----------------------------------------------------------------------
    // Security
    // ----------------------------------------------------------------------

    public DbSet<ApplicationUserExtend> ApplicationUserExtends { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {           
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
        modelBuilder.Entity<ApplicationUser>().ToTable("ApplicationUser");

    }

} 

public partial class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> 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;
    }
    //custom+
    public virtual ApplicationUserExtend Extend { get; set; }

}

public class ApplicationUserExtend
{
    public ApplicationUserExtend()
    {

    }

    [Key]
    [Display(Name="Id")]
    [XmlAttribute]
    public int Id { get; set; }


    [Display(Name="Account Id")]
    [XmlAttribute]
    public int AccountId { get; set; }


    [Display(Name="Active Account Id")]
    [XmlAttribute]
    public int ActiveAccountId { get; set; }
}



public class RqInitializer : System.Data.Entity.DropCreateDatabaseAlways<RqDbContext>
{
    protected override void Seed(RqDbContext context)
    {

        var testData = ReadTestData();

        AddIdentityRoles(context, testData);
        AddUsers(context, testData);

        MvcUtil.SaveChanges(context);
    }

    private void AddUsers(RqDbContext context, TestDataDo testData)
    {
        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
        //Roles.Enabled("user","member");
        var userIndex = 0;

        foreach (var applicationUser in testData.ApplicationUsers)
        {
            var user = new ApplicationUser
            {
                UserName = applicationUser.UserName,
                Email = applicationUser.Email,
                PhoneNumber = applicationUser.PhoneNumber
            };

            if (userIndex > testData.ApplicationUserExtends.Count)
            {
                throw new Exception("Make sure you the number of rows in ApplicationUserExtends, matches the number of rows in Users");
            }

            user.Extend = new ApplicationUserExtend
            {
                AccountId = testData.ApplicationUserExtends[userIndex++].AccountId
            };

            userManager.Create(user, applicationUser.Password);
            //set User Role
            userManager.AddToRole(user.Id, applicationUser.Role);

            //context.Users.Add(user);
        }
        context.SaveChanges();
    }
    private void AddIdentityRoles(RqDbContext context, TestDataDo testData)
    {
        var roleStore = new RoleStore<IdentityRole>(context);
        var roleManager = new RoleManager<IdentityRole>(roleStore);

        foreach (var role in testData.IdentityRoles)
        {
            var identity = new IdentityRole(role.Name);

            roleManager.Create(identity);
        }

        context.SaveChanges();
    }

    public static TestDataDo ReadTestData()
    {
        var xml = GetResource("Rq.Web.App_Specification.Rq-TestData.xml");
        return XmlUtil.SerializeFromString<TestDataDo>(xml);
    }

    private static string GetResource(string file)
    {
        var assembly = Assembly.GetExecutingAssembly();
        return ResourceUtil.GetAsString(assembly, file);
    }
}

// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<RqDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}
公共类RqDbContext:DbContext { 私有常量字符串ConnectionString=“RqDbContext”; 公共RqDbContext():基本(连接字符串) { } 公共静态RqDbContext Create() { 返回新的RqDbContext(); } // ---------------------------------------------------------------------- //数据表 // ---------------------------------------------------------------------- 公共数据库集引号{get;set;} 公共数据库集预订{get;set;} 公共数据库集公司帐户{get;set;} // ---------------------------------------------------------------------- //保安 // ---------------------------------------------------------------------- 公共数据库集ApplicationUserExtends{get;set;} 模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder) { 基于模型创建(modelBuilder); modelBuilder.Entity().HasKey(l=>l.UserId); modelBuilder.Entity().HasKey(r=>r.Id); modelBuilder.Entity().HasKey(r=>new{r.RoleId,r.UserId}); modelBuilder.Entity().ToTable(“ApplicationUser”); } } 公共部分类应用程序用户:IdentityUser { 公共异步任务GenerateUserIdentityAsync(用户管理器) { //注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配 var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie); //在此处添加自定义用户声明 返回用户身份; } //习俗+ 公共虚拟应用程序SerExtend扩展{get;set;} } 公共类ApplicationUserExtend { 公共应用程序serextend() { } [关键] [显示(Name=“Id”)] [XmlAttribute] 公共int Id{get;set;} [显示(名称=“帐户Id”)] [XmlAttribute] public int AccountId{get;set;} [显示(Name=“活动帐户Id”)] [XmlAttribute] public int ActiveAccountId{get;set;} } 公共类RqInitializer:System.Data.Entity.DropCreateDatabaseAlways { 受保护的覆盖无效种子(RqDbContext上下文) { var testData=ReadTestData(); AddIdentityRoles(上下文、测试数据); 添加用户(上下文、测试数据); MvcUtil.SaveChanges(上下文); } 私有void AddUsers(RqDbContext上下文,TestDataDo testData) { var userStore=新的userStore(上下文); var userManager=newusermanager(userStore); //角色。已启用(“用户”、“成员”); var userIndex=0; foreach(testData.ApplicationUsers中的var applicationUser) { var user=新应用程序用户 { UserName=applicationUser.UserName, Email=applicationUser.Email, PhoneNumber=applicationUser.PhoneNumber }; if(userIndex>testData.ApplicationUserExtends.Count) { 抛出新异常(“确保ApplicationUserExtends中的行数与用户中的行数匹配”); } user.Extend=新应用程序serextend { AccountId=testData.ApplicationUserExtends[userIndex++].AccountId }; 创建(用户、应用程序用户、密码); //设置用户角色 userManager.AddToRole(user.Id,applicationUser.Role); //context.Users.Add(用户); } SaveChanges(); } 私有void AddIdentityRoles(RqDbContext上下文,TestDataDo testData) { var roleStore=新roleStore(上下文); var roleManager=新roleManager(roleStore); foreach(testData.IdentityRoles中的var角色) { var identity=newidentityrole(role.Name); 角色管理器。创建(标识); } SaveChanges(); } 公共静态TestDataDo ReadTestData() { var xml=GetResource(“Rq.Web.App_Specification.Rq TestData.xml”); 返回XmlUtil.SerializeFromString(xml); } 私有静态字符串GetResource(字符串文件) { var assembly=assembly.getExecutionGassembly(); 返回ResourceUtil.GetAsString(程序集,文件); } } //配置此应用程序中使用的应用程序用户管理器。UserManager在ASP.NET标识中定义,并由应用程序使用。 公共类应用程序管理员:UserManager { 公共应用程序服务器管理器(IUserStore存储) :基地(商店) { } 公共静态应用程序SerManager创建(IdentityFactoryOptions选项,IOwinContext上下文) { var manager=newapplicationUserManager(newuserstore(context.Get()); //为用户名配置验证逻辑 manager.UserValidator=新的UserValidator(管理器) { AllowOnlyAlphanumericUserNames=false, RequireUniqueEmail=true }; //配置验证
var user = modelBuilder.Entity<TUser>()
    .ToTable("AspNetUsers");
user.HasMany(u => u.Roles).WithRequired().HasForeignKey(ur => ur.UserId);
user.HasMany(u => u.Claims).WithRequired().HasForeignKey(uc => uc.UserId);
user.HasMany(u => u.Logins).WithRequired().HasForeignKey(ul => ul.UserId);
user.Property(u => u.UserName).IsRequired();

modelBuilder.Entity<TUserRole>()
    .HasKey(r => new { r.UserId, r.RoleId })
    .ToTable("AspNetUserRoles");

modelBuilder.Entity<TUserLogin>()
    .HasKey(l => new { l.UserId, l.LoginProvider, l.ProviderKey})
    .ToTable("AspNetUserLogins");

modelBuilder.Entity<TUserClaim>()
    .ToTable("AspNetUserClaims");

var role = modelBuilder.Entity<TRole>()
    .ToTable("AspNetRoles");
role.Property(r => r.Name).IsRequired();
role.HasMany(r => r.Users).WithRequired().HasForeignKey(ur => ur.RoleId);