[英]get current user email in 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<IIdentity>().Use(() => GetIdentity());
在我的 IoC 容器[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<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;
希望这可以帮助...
家庭控制器
[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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.