2016-07-26 77 views
1

在我的項目ASP中,我使用的是ASP.NET Identity 2.2.1。在許多地方,我必須獲得當前(登錄)的用戶電子郵件。 現在,我發現使用這個用戶:獲取用戶電子郵件的Security.Principal.IIdentity擴展方法

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>()); 
var email = user.Email; 

我注意到GetUserId<T>的是,可以在裏面IdentityExtensions類中找到裏面Microsoft.AspNet.Identity

我已經創建了自己的擴展方法擴展方法它簡化了通過允許把它作爲獲取電子郵件:

var email = User.Identity.GetUserEmail() 

下面是我的分機:

public static class MyIIdentityExtensions 
{ 
    public static string GetUserEmail(this IIdentity identity) 
    { 
     if (identity == null) 
     { 
      throw new ArgumentNullException("identity"); 
     } 
     var ci = identity as ClaimsIdentity; 
     if (ci == null) return null; 
     var um = HttpContext.Current.GetOwinContext().GetUserManager<UserManager>(); 
     if (um == null) return null; 
     var user = um.FindById(ci.GetUserId<int>()); 
     if (user == null) return null; 
     return user.Email; 
    } 
} 

,但比它build-in extension methods

複雜得多我可以簡化這個?也許有建立這樣做的方法?我想要的是從User.Identity當前登錄的用戶獲取Email的簡單方法。

回答

2

如果使用UserManager,則每次調用GetUserEmail方法時都會觸擊數據庫。

相反,您可以將電子郵件添加爲聲明。裏面ApplicationUser類有GenerateUserIdentityAsync方法

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(ClaimTypes.Email, this.Email)); 
    return userIdentity; 
} 

那麼你的擴展方法來得到它

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

我完全忘了'GenerateUserIdentityAsync'方法。我甚至有同樣的評論'//在這裏添加自定義用戶聲明。我還有一個額外的問題:我可以從用戶登錄時返回的JWT令牌中刪除該聲明嗎?我想要的是返回JWT令牌內的最小數據集。但從另一方面來說,如果我在所有請求中從標記中刪除該聲明,我將無法獲得該電子郵件地址,因爲我不會獲得該聲明。 – Misiu

+0

@Misiu那條評論是從默認mvc5模板:) 關於你的額外問題,它不清楚你想要什麼。您想要在某些請求上添加索賠? – tmg

+0

對不起,感到困惑。我希望在服務器端可以訪問該聲明,但不能發送給JWT令牌內的客戶端。也許這是不可能的,但我想確定。 – Misiu

相關問題