[英]Get first name and last name of User.identity
我有一個使用Windows身份驗證設置的Intranet應用程序。 我需要在標題中顯示用戶名和用戶的縮寫,例如:
歡迎jSmith JS
到目前為止,我做了什么:
<div class="header__profile-name">Welcome <b>@User.Identity.Name.Split('\\')[1]</b></div>
<div class="header__profile-img">@User.Identity.Name.Split('\\')[1].Substring(0, 2)</div>
問題在於用戶名並不總是姓和名的首字母,有時用戶名可以是ex的名字和名的首字母:
John Smith-用戶名可以是jsmith,但有時也可以是: johns
在那種情況下,我的代碼是錯誤的,因為它將導致:
用jo代替js
如何獲取完整的用戶名:帶有User.identity
名字和User.identity
?
然后,我將基於完整的用戶名(名字和姓氏)創建代碼,以設置縮寫名,而不是基於並非始終一致的用戶名。
在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 "";
}
更新
或者您可以在創建用戶時將其添加到用戶的聲明中,然后從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
更新
對於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
下添加它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.