为了支持tenan/companies,我在ASP MVC 5,身份2.2角色管理中添加/扩展了一个名为OrgId
的新AspUser Table
属性,我将相应的OrgId添加到其他一些表中,查看此处但没有答案
在用户Login()
和UserSession
期间
- 如何缓存、配置和检索 OrgId,以便我可以对组织特定记录的表执行 DBConext 过滤/CRUD?
- 建议:最好将其保存在声明,FormsToken或会话中 - 并且 如何在会话中设置 tenanId 上下文?
我知道如何获取用户,但不知道扩展组织
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
自定义的用户类应如下所示:
public class CustomizedUser : IdentityUser
{
public int OrgId {get; set;}
public DateTime JoinDate { get; set; }
//...
// and other simple fields
//Fields related to other tables
public virtual ICollection<Article> Articles { get; set; } = new List<Article>();
//...
}
和你的 CustomizedApplicationDbContext 类
public class CustomizedApplicationDbContext : IdentityDbContext<CustomizedUser>, IApplicationDbContext
{
public CustomizedApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static CustomizedApplicationDbContext Create()
{
return new CustomizedApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//your entity configurations go here if you have any
base.OnModelCreating(modelBuilder);
}
//These fields are neccessary in order to maintain the power of base class
public DbChangeTracker Changetracker => base.ChangeTracker;
public Database DatabBase => base.Database;
//your own dbsets go here except CustomizedUser, because the base class IdentityDbContext<CustomizedUser> handles it
public IDbSet<Article> Articles { get; set; }
//...
}
现在,请记住将代码中的每个 ApplicationDbContext 引用替换为 CustomizedApplicationDbContext,并将每个 IdentityUser 引用替换为 CustomizedUser(特别是在 mvc 创建的 ManageController 中)。
从现在开始,您可以像其他表一样轻松访问用户表:
var db = new CustomizedApplicationDbContext();
var user = db.CustomizedUsers.First(x=> x.OrgId == 10 || Email == "sth@yahoo.com");
要获取当前用户 OrgId,您可以使用这样的东西(不查询 db):
var currentUserOrgId = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId()).OrgId;
希望这是有帮助的
您可以在ASP.NET Identity
中获取当前用户,如下所示:
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext()
.GetUserManager<ApplicationUserManager>()
.FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
//If you use int instead of string for primary key, use this:
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext()
.GetUserManager<ApplicationUserManager>()
.FindById(Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.GetUserId()));
要从表中获取自定义属性AspNetUsers
请执行以下操作:
ApplicationUser user = UserManager.FindByName(userName);
string name = user.Name;
希望这有帮助...