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

时间:2017-03-01 13:13:33

标签: 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;
}

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

用法

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

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

示例

this._identity.GetEmailAdress();

使用this._identity.GetUserName();时,请勿获取用户名数据库

3 个答案:

答案 0 :(得分:4)

你可以在这些方面做点什么:

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();

答案 1 :(得分:3)

您可以在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()));


AspNetUsers表中获取自定义属性:

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

希望这会有所帮助......

答案 2 :(得分:0)

家庭控制器

 [AllowAnonymous]
        public ActionResult GetUserEmail()
        {
            try
            {
                var userID = User.Identity.GetUserId();
                ViewBag.EmailData = db.AspNetUsers.Where(s => s.Id == userID).Select(x => x.Email).FirstOrDefault().ToString();
                return Content(ViewBag.EmailData);
            }
            catch
            {
                return null;
            }
        }

在视图中

@{
string USREmail = Html.Action("GetUserEmail", "Home").ToString();
}

您可以显示电子邮件

@USREmail