获取Identity中的当前用户电子邮件
我使用IIdentity
接口获取当前userid
和username
。
所以实现以下方法:
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; }
并添加以下代码: _.For().Use(() => GetIdentity());
在我的IoC Container [structuremap]
。
用法
this._identity.GetUserId(); this._identity.GetUserName(); this._identity.IsAuthenticated
现在我想实现GetEmailAdress
方法,如何做到这一点?
例
this._identity.GetEmailAdress();
当使用this._identity.GetUserName();
不要获取用户名表格数据库 。
你可以在这些方面做点什么:
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();
您可以在ASP.NET Identity
获取当前用户,如下所示:
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext() .GetUserManager() .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 () .FindById(Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.GetUserId()));
要从AspNetUsers
表获取自定义属性:
ApplicationUser user = UserManager.FindByName(userName); string mail= user.Email;
希望这可以帮助…