在Identity中获取当前用户的电子邮件

Soh*_*deh 5 c# asp.net-mvc identity

我使用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;
}
Run Code Online (Sandbox Code Playgroud)

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

用法

this._identity.GetUserId();
this._identity.GetUserName();
this._identity.IsAuthenticated
Run Code Online (Sandbox Code Playgroud)

现在我想实施GetEmailAdress方法,如何做到这一点?

this._identity.GetEmailAdress();
Run Code Online (Sandbox Code Playgroud)

使用时this._identity.GetUserName();不要获取用户名表格数据库.

Jin*_*ish 5

你可以在这些行上做一些事情:

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;
        }
    }        
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以像这样访问它:

this._identity.GetEmailAdress();
Run Code Online (Sandbox Code Playgroud)

  • 是的,因为用户名是您的校长的一部分,而不是电子邮件。除非您在应用程序中使用声明,否则您必须从数据库获取电子邮件。在这种情况下,您可以在对用户进行身份验证时在声明中设置它,然后从声明中读取它。 (2认同)

Mur*_*dız 5

您可以获取当前用户,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()));
Run Code Online (Sandbox Code Playgroud)
要从“AspNetUsers”表获取自定义属性:
ApplicationUser user = UserManager.FindByName(userName);
string mail= user.Email;
Run Code Online (Sandbox Code Playgroud)

  • @SoheilAlizadeh 用户名是一回事。用户的电子邮件是另一个。您无法从身份中获取个人资料信息,就像要求从护照、身份证或驾照中获取电子邮件一样。这里没有什么需要解决的 - 声明“仍然”是一种身份形式。此外,您可以使用一个电子邮件地址作为您的用户名,另一个作为您的联系电子邮件 (2认同)