gpt4 book ai didi

c# - 如何在asp.net core中添加多个身份和多个角色

转载 作者:行者123 更新时间:2023-12-04 12:32:30 25 4
gpt4 key购买 nike

我是asp.net核心的新手。所以这可能不是一个好问题。
我有 3 个类(class):Admin , Doctor , Patient .
我希望所有这些用户都能够登录并查看他们的仪表板。所有这些都将具有不同级别的访问权限。
所以我从 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; }
}
我只是被困在这之后。
当我尝试通过方法 AddIdentity<TUser, TRole>() 添加多个身份时,它给了我错误。
我接下来该怎么做?
网上大部分例子都涉及一个 IdentityUser和多个 IdentityRole .但由于用户模型都不同,我不能那样做。
谢谢你。

最佳答案

您不能重复使用 AddIdentity添加身份。
ASP.NET Core 提供了一个内置方法:AddIdentityCore<TUser> .
你可以这样使用它:services.AddIdentityCore<Admin>(); 编辑:
添加到银秋的回答中,对于 future 的读者,如果您使用此AddIdentityCore方法,AspNetUsers table 将合并每个 IdentityUser 的所有属性.下面是一个例子:
TeacherStudent是两个 IdentityUser并且它们都至少有一个不同的属性,如下所示:

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

public class Student : IdentityUser
{
public int Grade { get; set; }
}
然后我在 startup.cs 中添加了他们的身份。像这样:
services.AddIdentityCore<Teacher>().AddEntityFrameworkStores<AppDbContext>();
services.AddIdentityCore<Student>().AddEntityFrameworkStores<AppDbContext>();
AspNetUsers 表将包括 Subject属性(property)和 Grade属性(property)。这是迁移类的证明:
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);
});
注意最后两个属性是 GradeSubject .
这类似于为所有 IdentitiyUser 使用基类这将派生自 IdentityUser并包含所有属性的组合,然后使用 AddIdentity<TUser, TRole> 添加一个基类方法。

关于c# - 如何在asp.net core中添加多个身份和多个角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64370175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com