2016-08-09 24 views
5

W modelu ASP.Net MVC 5 można rozszerzyć ApplicationUser, aby uzyskać niestandardową właściwość. Mam rozszerzone to takie, że ma teraz nową właściwość o nazwie DisplayName:Jak uzyskać niestandardową wartość właściwości ApplicationUser w widoku ASP.Net MVC 5?

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

Mam też zaktualizowaną tabelę bazy danych przy użyciu polecenia Update-Database w Package-Manager Console w Visual Studio w celu zapewnienia spójności między ApplicationUserclass a stołem AspNetUsers. Potwierdziłem, że nowa kolumna o nazwie DisplayName istnieje już w tabeli AspNetUsers.

enter image description here

Teraz chcę użyć tego DisplayName zamiast domyślnego UserName na tekst w oryginalnym _LoginPartial.cshtmlView. Ale jak widać:

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

Oryginalny _LoginPartialView.cshtml korzysta User.Identity.GetUserName() uzyskać UserName z ApplicationUser. User.Identity ma GetUserId, a także Name, AuthenticationType, itp. ... Ale jak mogę uzyskać mój DisplayName do wyświetlenia?

Odpowiedz

5

Dodaj roszczenia w 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; 
    } 
} 

Stworzył metodę EXTENTION czytać DisplayName z 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;   
    } 
} 

W widoku używać go jak:

User.Identity.GetDisplayName() 
+0

To wygląda obiecująco ... gdzie zwykle umieszczasz swoją metodę "IdentiyExtensions"? W "IdentityModels.cs"? A może utworzysz nowy plik z określoną konwencją nazw? – Ian

+0

Utworzę nowy plik o nazwie "IdentityExtensions.cs", prawdopodobnie w folderze o nazwie "Helpers" – tmg

+0

Dziękuję za odpowiedź! To działa! Wprowadzam jednak niewielką modyfikację ... zamiast zwracać 'return claim.FindFirst (" DisplayName ")', zwracam 'return claim.FindFirst (" DisplayName ") ToString(). Substring ((" DisplayName: "). Length); '- to dlatego, że' claim.FindFirst ("DisplayName") 'jest typu' Claim', ale 'return' musi być' string'. Ponadto, jeśli nie wstawię 'Substringa ', wyświetli on' DisplayName: myname' zamiast tylko 'myname'. – Ian