在我的应用程序中,我使用的是ASP.NET身份,我有不同类型的用户(教师,学生,...),他们有自己的属性,对于老师我有Experience, Languages Spoken, Certifications, Awards, Affiliations, ...
而对于学生我有不同的属性。因此,由于每个用户的信息不同,我无法使用角色。所以他们实际上都是用户,我的意思是他们可以登录我的网站。此外,他们还有注册的常用信息:First Name, Last Name, Email, Password
现在你认为什么以及做这件事的最佳选择是什么?我应该为继承自IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
的每个用户创建类吗?
有什么想法吗?
PS :我已经找到了一些解决方法,例如here建议使用声明但是对我来说还不够明确,实际声称这是难题的一部分,我没有得到它们是什么? :),最好有例子。谢谢
答案 0 :(得分:9)
Apporach#1:
索赔方法可能是最佳选择。因此,您以正常方式从IdentityUser
派生,并将公共属性添加到派生类。然后,对于每种类型的用户,您都可以使用UserManager.AddClaimAsync
添加额外的声明。
因此,例如,假设您创建了一个名为AppUser
的新类用户类。然后你可以这样做:
AppUser teacher = new AppUser { /* fill properties here */ };
/* Save User */
await userManager.AddClaimAsync(teacher.Id, new Claim("app_usertype", "teacher"));
await userManager.AddClaimAsync(teacher.Id, new Claim("app_grade", 4));
await userManager.AddClaimAsync(teacher.Id, new Claim("app_exp", 10));
await userManager.AddClaimAsync(teacher.Id, new Claim("app_awards", "Award1,Award2"));
await userManager.AddClaimAsync(teacher.Id, new Claim("app_langspoken", "English,French,German"));
AppUser student = new AppUser { /* fill properties here */ };
/* Save User */
await userManager.AddClaimAsync(student.Id, new Claim("app_usertype", "student"));
await userManager.AddClaimAsync(student.Id, new Claim("app_grade", 2));
这些会为不同类型的用户添加不同的声明。因此,teacher
声称拥有&#34; app_experience&#34; of&#34; 10&#34;,&#34; app_awards&#34; &#34; Award1&#34;和#34; Award2&#34;等。另一方面,student
声称只有&#34; app_grade&#34; &#34; 2&#34;。
基本上,第一个参数标识声明的类型,第二个参数是备份声明的数据。类型可以是任何类型,因此请选择对您的应用程序有意义的内容,并为每个名称添加前缀以区别于其他名称。如果我只是前缀&#34; app&#34;。
然后,您可以使用UserManager.GetClaimsAsync
获取用户的所有声明,并在返回的列表中搜索您感兴趣的声明。
方法#2
另一种方法是创建一个AppUser
类,然后创建Teacher
和Student
类,该类派生自AppUser
。在这些类中,您将添加在上面的示例中将作为声明添加的属性。
这方面的一个小缺点是,您必须为这些不同用户中的每一个创建单独的表,并将关系返回到ASP.NET Identity用户表。
另外,使用FindByUserNameAsync
,FindByEmailAsync
等只会返回一种TUser
,在本例中为AppUser
。此外,这些方法只会查询一个表AspNetUsers
,因此您可以从相关的Teacher
或Student
表中获取额外信息。
答案 1 :(得分:1)
由于所有用户都拥有一些相同的属性,因此创建一个&#34; User&#34; class,用于保存教师,学生等所有相同的属性。
然后,我会为每个用户类型创建一个类,其中只包含特定于该类型用户的属性。在这个类中,我将UserId作为其中一个属性包含在内,这样您就可以从主组到各个类型之间建立关系。见下文:
用户类: UserId(主键), 名字, 姓, 登录, 密码, 等
老师班: UserId(外键), 等级, 经验, 奖, 等
学生班: UserId(外键), 年级, 荣誉, 等
有很多方法可以做你想要的事情所以这只是一个建议。祝你好运!