2016-02-06 62 views
4

我添加了一些新的屬性asp.net身份2.2.1(AspNetUsers表)代碼首先如何另一個Propertys加入User.Identity從表AspNetUsers身份2.2.1

public class ApplicationUser : IdentityUser 
    { 
     public string AccessToken { get; set; } 

     public string FullName { get; set; } 

     public string ProfilePicture { 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 

      return userIdentity; 
     } 
    } 

好了,現在我想打電話頭像像這樣的代碼: User.Identity.ProfilePicture;

的解決方案是:

你需要創建一個實施的IIdentity和 IPrincipal的自己的類。然後在 OnPostAuthenticate分配他們在您的Global.asax。

但我不知道如何做到這一點!如何創建自己的實現IIdentity和IPrincipal的類。然後在OnPostAuthenticate的global.asax中分配它們。 謝謝。

回答

8

你有2個選項(至少)。首先,在用戶登錄時將您的附加屬性設置爲索賠,然後在您每次需要時從索賠中讀取屬性。其次,每次您需要從存儲(DB)中讀取屬性時。雖然我建議基於索賠的方法更快,但我會通過使用擴展方法向您展示這兩種方法。

第一種方法:

把自己的要求在GenerateUserIdentityAsync方法是這樣的:

public class ApplicationUser : IdentityUser 
{ 
    // some code here 

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     userIdentity.AddClaim(new Claim("ProfilePicture", this.ProfilePicture)); 
     return userIdentity; 
    } 
} 

然後寫一個擴展方法來輕鬆地閱讀這樣的要求:

public static class IdentityHelper 
{ 
    public static string GetProfilePicture(this IIdentity identity) 
    { 
     var claimIdent = identity as ClaimsIdentity; 
     return claimIdent != null 
      && claimIdent.HasClaim(c => c.Type == "ProfilePicture") 
      ? claimIdent.FindFirst("ProfilePicture").Value 
      : string.Empty; 
    } 
} 

現在你可以很容易地使用你的擴展方法是這樣的:

var pic = User.Identity.GetProfilePicture(); 

方法二:

如果你喜歡新鮮的數據,而不是要求在兌現一個,你可以寫另一個擴展方法來得到用戶管理屬性:

public static class IdentityHelper 
{ 
    public static string GetFreshProfilePicture(this IIdentity identity) 
    { 
     var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
     return userManager.FindById(identity.GetUserId()).ProfilePicture; 
    } 
} 

現在簡單地使用這樣的:

var pic = User.Identity.GetFreshProfilePicture(); 

也不要忘了添加有關namespac ES:

using System.Security.Claims; 
using System.Security.Principal; 
using System.Web; 
using Microsoft.AspNet.Identity.Owin; 
using Microsoft.AspNet.Identity; 
+0

非常感謝你:) – MoHaMmAd