我是 MVC 5 asp.net Identity 模型的新手,正在寻找自定义标准 Asp.net Identity 以满足我的需求的方法。通过博客 TypeCast Exception和一个在 Stackoverflow: How to model Identity我能够在 ApplicationUser 和 ApplicationRole 表中创建自己的元素。但是,我的要求是向 UserRole 表、DATE_FROM 和 DATE_TO 添加新列,这是我通过实现 IdentityUserRole
所做的。界面。我的问题是当我试图保存链接时 UserManager.AddRoleToUser 只需要两个参数,UserName 和 RoleName。如何存储自定义参数 ApplicationUserRole
?
public bool AddUserToRole(string userId, SelectUserRolesViewModel roleName)
{
var um = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(new ApplicationDbContext()));
var idResult = um.AddToRole(userId, roleName);
return idResult.Succeeded;
}
SelectUserRolesViewModel 提供扩展的 IdnetityUserRole 模型。任何指针将不胜感激。
最佳答案
如果向 ApplicationUserRole 表添加其他属性,则不能使用 AddUserToRole
方法了。因为 AddUserToRole
方法来自 UserManagerExtensions
类是密封类,您不能创建自己的类来继承 UserManagerExtensions
.我不确定是否有更好的解决方案,但下面是一个工作示例。
向 ApplicationUserRole
添加其他属性 table :
public class ApplicationUserRole : IdentityUserRole
{
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<ApplicationUserRole> ApplicationUserRoles { get; set; }
}
然后你可以新建一个
ApplicationUserRole
实例如下: using (var _db = new ApplicationDbContext())
{
var roleName = //Get role name from somewhere here
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_db));
if (!roleManager.RoleExists(roleName))
{
var newRoleresult = roleManager.Create(new IdentityRole()
{
Name = roleName,
});
}
var userRole = new ApplicationUserRole
{
UserId = currentUser.Id,
RoleId = roleManager.FindByName(roleName).Id,
DateFrom = DateTime.Now,
DateTo = DateTime.Now.AddDays(1)
};
_db.ApplicationUserRoles.Add(userRole);
_db.SaveChanges();
}
关于asp.net-mvc - MVC 5 : Asp.net Identity:如何对 UserRole 建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21680501/