在 ApplicationUser 类中,您会注意到一条注释(如果您使用标准 MVC5 模板):“在此处添加自定义用户声明”。
鉴于此,添加 FullName 的样子如下:
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
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
userIdentity.AddClaim(new Claim("FullName", this.FullName));
return userIdentity;
}
}
使用此功能,当有人登录时,FullName 声明将被放入 cookie 中。您可以创建一个助手来访问它,如下所示:
public static string GetFullName(this System.Security.Principal.IPrincipal usr)
{
var fullNameClaim = ((ClaimsIdentity)usr.Identity).FindFirst("FullName");
if (fullNameClaim != null)
return fullNameClaim.Value;
return "";
}
Update
Or您可以在创建用户时将其添加到用户的声明中,然后从 User.Identity 中将其作为声明检索:
await userManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));
检索它:
((ClaimsIdentity)User.Identity).FindFirst("FullName")
或者您可以直接获取用户并从 user.FullName 访问它:
var user = await userManager.FindById(User.Identity.GetUserId())
return user.FullName
Update
for intranet
你可以这样做:
using (var context = new PrincipalContext(ContextType.Domain))
{
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
var firstName = principal.GivenName;
var lastName = principal.Surname;
}
您需要添加对System.DirectoryServices.AccountManagement
集会。
您可以像这样添加 Razor 助手:
@helper AccountName()
{
using (var context = new PrincipalContext(ContextType.Domain))
{
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
@principal.GivenName @principal.Surname
}
}
如果您打算从视图而不是控制器执行此操作,则还需要向 web.config 添加程序集引用:
<add assembly="System.DirectoryServices.AccountManagement" />
添加到下面configuration/system.web/assemblies
.