如何在asp.net core中添加多重身份和多重角色

Muz*_*zib 6 c# asp.net entity-framework entity-framework-core asp.net-core

我是 ASP.NET Core 的新手。所以这可能不是一个好问题。

我有 3 个课程:AdminDoctorPatient

我希望所有这些用户都能够登录并查看他们的仪表板。他们所有人都将具有不同级别的访问权限。

IdenetityUser所以我从这样的方式派生出这些类:

public class Admin : IdentityUser
{
}

public class Doctor : IdentityUser
{
    public const int MaxAppointPerDay = 28;

    public Gender Gender { get; set; }
}

public class Patient : IdentityUser
{
    public DateTime DateOfBirth { get; set; }
    public Gender Gender { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我只是被困在这之后。

当我尝试通过该方法添加多个身份时AddIdentity<TUser, TRole>(),它给了我错误。

接下来我该怎么办?

互联网上的大多数例子都涉及一个IdentityUser和多个IdentityRole。但由于用户模型各不相同,我不能这样做。

谢谢。

Yin*_*qiu 6

您不能重复使用AddIdentity添加身份。

ASP.NET Core 提供了一个内置方法:AddIdentityCore<TUser>.

你可以这样使用它:services.AddIdentityCore<Admin>();

编辑:

添加到 Yinqiu 的答案中,对于未来的读者,如果您使用此AddIdentityCore方法,该AspNetUsers表将合并每个 的所有属性IdentityUser。这是一个例子:

TeacherStudent是两个IdentityUser,并且它们都至少具有一个不同的属性,如下所示:

public class Teacher : IdentityUser
{
    public string Subject { get; set; }
}

public class Student : IdentityUser
{
    public int Grade { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我添加他们的身份,如下所示startup.cs

services.AddIdentityCore<Teacher>().AddEntityFrameworkStores<AppDbContext>();
services.AddIdentityCore<Student>().AddEntityFrameworkStores<AppDbContext>();
Run Code Online (Sandbox Code Playgroud)

AspNetUsers表将包含属性和属性。这是迁移类的证明:SubjectGrade

migrationBuilder.CreateTable(
    name: "AspNetUsers",
    columns: table => new
    {
        Id = table.Column<string>(nullable: false),
        UserName = table.Column<string>(maxLength: 256, nullable: true),
        NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
        Email = table.Column<string>(maxLength: 256, nullable: true),
        NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
        EmailConfirmed = table.Column<bool>(nullable: false),
        PasswordHash = table.Column<string>(nullable: true),
        SecurityStamp = table.Column<string>(nullable: true),
        ConcurrencyStamp = table.Column<string>(nullable: true),
        PhoneNumber = table.Column<string>(nullable: true),
        PhoneNumberConfirmed = table.Column<bool>(nullable: false),
        TwoFactorEnabled = table.Column<bool>(nullable: false),
        LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
        LockoutEnabled = table.Column<bool>(nullable: false),
        AccessFailedCount = table.Column<int>(nullable: false),
        Discriminator = table.Column<string>(nullable: false),
        Grade = table.Column<int>(nullable: true),
        Subject = table.Column<string>(nullable: true)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_AspNetUsers", x => x.Id);
    });
Run Code Online (Sandbox Code Playgroud)

请注意最后两个属性是GradeSubject

这类似于对所有IdentitiyUser派生自所有属性IdentityUser并包含所有属性的组合使用基类,然后仅使用方法添加该基类AddIdentity<TUser, TRole>