2017-03-01 24 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

我认为,可以通过索赔解决这个问题。 –

相关问题