我使用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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句