How to get custom value of ApplicationUser property in ASP.Net MVC 5 View?

In ASP.Net MVC 5 , ApplicationUser can be extended to have a custom property. I expanded it so that now it has a new DisplayName property:

 // 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<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; } } 

I also updated the database table using the Update-Database command in the Package-Manager Console in Visual Studio to ensure consistency between the ApplicationUser class and AspNetUsers . I confirmed that a new column named DisplayName now exists in the AspNetUsers table.

enter image description here

Now I want to use this DisplayName instead of the standard UserName for the text in the original _LoginPartial.cshtml View . But as you can see:

 <ul class="nav navbar-nav navbar-right"> <li> @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" }) </li> <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> </ul> 

The original _LoginPartialView.cshtml uses User.Identity.GetUserName() to get the UserName ApplicationUser . User.Identity has GetUserId as well as Name , AuthenticationType , etc. But how do I get my DisplayName to display?

+5
c # asp.net-mvc asp.net-mvc-5 asp.net-identity
Aug 09 '16 at 9:23
source share
1 answer

Add a claim to ClaimsIdentity:

 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 userIdentity.AddClaim(new Claim("DisplayName", DisplayName)); return userIdentity; } } 

An extension method has been created to read DisplayName from ClaimsIdentity:

 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; } } 

In your view, use it like:

 User.Identity.GetDisplayName() 
+5
Aug 09 '16 at 9:32
source share



All Articles