Soh*_*deh 5 c# asp.net-mvc 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;
}
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();不要获取用户名表格数据库.
你可以在这些行上做一些事情:
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)
您可以获取当前用户,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)
ApplicationUser user = UserManager.FindByName(userName);
string mail= user.Email;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13345 次 |
| 最近记录: |