我正在使用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();
然而,User.Identity中没有可用的OrganizationId属性。我需要扩展User.Identity以包含OrganizationId属性吗?如果是这样,我该如何操作?
我经常需要使用OrganizationId,因为许多表查询都依赖于OrganizationId来检索与已登录用户关联的组织相关的数据。