2017-03-01 78 views
0

我使用IIdentity接口獲取當前useridusername以身份獲得當前用戶電子郵件

所以實現以下方法:

private static IIdentity GetIdentity() 
{ 
    if (HttpContext.Current != null && HttpContext.Current.User != null) 
    { 
     return HttpContext.Current.User.Identity; 
    } 

    return ClaimsPrincipal.Current != null ? ClaimsPrincipal.Current.Identity : null; 
} 

並添加以下代碼:我的IoC容器[structuremap]_.For<IIdentity>().Use(() => GetIdentity());

使用

this._identity.GetUserId(); 
this._identity.GetUserName(); 
this._identity.IsAuthenticated 

現在我想要實現GetEmailAdress方法,如何做到這一點?

this._identity.GetEmailAdress(); 

使用時this._identity.GetUserName();沒有得到用戶名形式數據庫

+0

電子郵件是從用戶的配置文件,而不是他的身份數據。您需要獲取當前用戶的配置文件對象,然後檢索他的電子郵件。 –

回答

3

你可以做一些在這些線路上:

public static class IdentityExtensions 
{ 
    public static string GetEmailAdress(this IIdentity identity) 
    { 
     var userId = identity.GetUserId(); 
     using (var context = new DbContext()) 
     { 
      var user = context.Users.FirstOrDefault(u => u.Id == userId); 
      return user.Email; 
     } 
    }   
} 

,然後你就可以訪問它想:

this._identity.GetEmailAdress(); 
+0

使用'this._identity.GetUserName();'不要從數據庫獲取用戶名。 –

+1

是的,因爲用戶名是你的校長的一部分,但不是電子郵件。除非您在應用程序中使用聲明,否則必須從數據庫獲取電子郵件。在這種情況下,您可以在對用戶進行身份驗證時將其設置在聲明中,然後從聲明中進行閱讀。 – Jinish

+0

好的,你可以告訴我怎麼做或編輯你的答案,......? –

1

可以得到ASP.NET Identity當前用戶,如下圖所示,您:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext() 
    .GetUserManager<ApplicationUserManager>() 
    .FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); 

//If you use int instead of string for primary key, use this: 
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext() 
    .GetUserManager<ApplicationUserManager>() 
    .FindById(Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.GetUserId())); 


對於獲取自定義屬性fr OM AspNetUsers表:

ApplicationUser user = UserManager.FindByName(userName); 
string mail= user.Email; 

希望這有助於...

+0

謝謝,@MuratYıldız我使用'ASP.NET身份',但我想得到像'this._identity.GetUserName();'這樣的數據庫沒有得到它的EmailAdress。 –

+0

@SoheilAlizadeh你可以嘗試用我的答案上的相關行更新實現的方法嗎?也許它解決了這個問題,你可以實現成功地使用已實現的方法。 –

+1

我認爲,可以通過索賠解決這個問題。 –

相關問題