Csharp/C#教程:在Identity 2.0中扩展IdentityUserRole分享


在Identity 2.0中扩展IdentityUserRole

因此,我的系统要求角色具有相关的到期日期。 我已经实现了Identity 2.0框架,事情进展顺利,但我遇到了一个让我怀疑我的结构的问题。

public class ApplicationUserRole : IdentityUserRole { public override string UserId { get; set; } public override string RoleId { get; set; } public DateTime Expiry { get; set; } } public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } static ApplicationDbContext() { Database.SetInitializer(null); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public DbSet ApplicationUserRoles { get; set; } } 

这就是我想要的。 它更改了AspNetUserRoles表,以便添加第三列,即DateTime,称为Expiry。 我可以使用ApplicationDBContext添加,更新和删除expiries,在编辑用户时一切正常。

问题出现在帐户创建上。 UserManager调用AddToRolesAsync,但只接受两个参数:User和Role。 我需要它来接受用户,角色和过期。

我需要实现自己的UserManager吗? 这似乎有点矫枉过正。

我能够解决这个问题,不允许在创建帐户时选择角色/到期时间,只需将其保留为编辑模式即可。 但我真的希望能够同时创建帐户并分配角色/到期日。

请查看以下video教程,了解如何使用现有数据库表使用asp.net身份。 我认为您必须让ApplicationUser表知道您的ApplicationUserRole表中有新字段。 因此,您必须遵循entity framework模型绑定才能实现这一点。

第1部分 – https://www.youtube.com/watch?v=elfqejow5hM

第2部分 – https://www.youtube.com/watch?v=JbSqi3Amatw

您不需要实现自己的userManager,但必须修改它。 希望您可以使用此示例来支持您的需求。

我知道这已经得到了解答 – 但是如果有人感兴趣 – 但是我没有使用UserManager.AddToRolesAsync,而是使用了新角色并使用了User的Role.Add()方法; 像这样:

上述就是C#学习教程:在Identity 2.0中扩展IdentityUserRole分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 var user = db.Users.Find(userId); foreach (string roleName in newRoles) { string roleId = RoleManager.FindByName(roleName).Id; var appUserRole = new ApplicationUserRole { UserId = user.Id, RoleId = roleId, CustomField1 = "value1", CustomField2 = "value2", .... }; user.Roles.Add(appUserRole); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/957125.html

(0)
上一篇 2021年11月21日
下一篇 2021年11月21日

精彩推荐