【发布时间】:2015-04-04 19:11:48
【问题描述】:
我正在使用 MVC5 Identity 2.0 让用户登录我的网站,其中身份验证详细信息存储在 SQL 数据库中。 Asp.net Identity 已以标准方式实现,可在许多在线教程中找到。
IdentityModels 中的 ApplicationUser 类已扩展为包含一些自定义属性,例如整数 OrganizationId。这个想法是可以创建许多用户并将其分配给一个公共组织以用于数据库关系。
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
//Extended Properties
public DateTime? BirthDate { get; set; }
public long? OrganizationId { get; set; }
//Key Mappings
[ForeignKey("OrganizationId")]
public virtual Organization Organization { get; set; }
}
如何从控制器中检索当前登录用户的 OrganizationId 属性? 这是否可以在用户登录后通过方法获得,还是每次控制器方法执行时我总是根据 UserId 从数据库中检索 OrganizationId?
在网上阅读我看到我需要使用以下内容来获取登录的 UserId 等。
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();
但是,OrganizationId 不是 User.Identity 中可用的属性。我是否需要扩展 User.Identity 以包含 OrganizationId 属性?如果是这样,我该怎么做。
我经常需要 OrganizationId 的原因是许多表查询依赖于 OrganizationId 来检索与登录用户关联的组织相关的数据。
【问题讨论】:
-
我的回答here对你有帮助吗?
-
我的回答几乎相同:stackoverflow.com/a/28138594/809357 - 如果您在请求的生命周期中经常需要此信息,您可以将其作为声明放在 cookie 中。
-
感谢@Shoe,您的两个回答都有效。除了您的答案之外,我还必须添加一个声明以存储在 cookie 中。在 IdentityModels 类中,我必须将 userIdentity.AddClaim(new Claim("MyApp:OrganizationId", OrganizationId.ToString())); 添加到 public async Task
GenerateUserIdentityAsync(UserManager 方法。manager)
标签: asp.net-mvc asp.net-mvc-5 asp.net-identity asp.net-identity-2