如何在ASP.Net MVC 5视图中获取ApplicationUser的自定义属性值?

ASP.Net MVC 5ApplicationUser可以扩展为具有自定义属性。 我已经扩展它,现在它有一个名为DisplayName的新属性:

 // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public string ConfirmationToken { get; set; } public string DisplayName { get; set; } //here it is! public async Task GenerateUserIdentityAsync(UserManager 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; } } 

我还使用Visual Studio中的Package-Manager Console中的Update-Database命令更新了数据库表,以确保ApplicationUser classAspNetUsers表之间的一致性。 我已经确认名为DisplayName的新列现在存在于AspNetUsers表中。

在此处输入图像描述

现在,我想使用DisplayName而不是原始_LoginPartial.cshtml View的文本的默认UserName 。 但正如你所看到的:

  

原始_LoginPartialView.cshtml使用User.Identity.GetUserName()来获取ApplicationUserUserNameUser.Identity具有GetUserId以及NameAuthenticationType等…但是如何显示我的DisplayName

在ClaimsIdentity中添加声明:

 public class ApplicationUser : IdentityUser { ... public async Task GenerateUserIdentityAsync(UserManager 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("DisplayName", DisplayName)); return userIdentity; } } 

创建了一个从ClaimsIdentity读取DisplayName的扩展方法:

 public static class IdentityExtensions { public static string GetDisplayName(this IIdentity identity) { if (identity == null) { throw new ArgumentNullException("identity"); } var ci = identity as ClaimsIdentity; if (ci != null) { return ci.FindFirstValue("DisplayName"); } return null; } } 

在您的视图中使用它像:

 User.Identity.GetDisplayName()