在applicationuser类中,您会注意到一条注释(如果使用标准的MVC5模板),上面写着“在这里添加自定义用户声明”。
考虑到这一点,下面是添加全名的过程:
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;
}
}
这样,当有人登录时,全名声明将被放入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 "";
}
更新
或
您可以在创建用户时将其添加到用户的声明中,然后将其作为声明从用户检索。标识:
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
更新
对于
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
装配。
您可以添加类似这样的剃刀助手:
@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
.