get current user email in Identity

Deadly 提交于 2019-12-10 14:58:33

问题


I use IIdentity interface For Getting current userid and username.

so implement following Method:

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;
}

And Add this code: _.For<IIdentity>().Use(() => GetIdentity()); in my IoC Container[structuremap].

Usage

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

Now I Want to Implement GetEmailAdress Method, How To do this?

Example

this._identity.GetEmailAdress();

When use this._identity.GetUserName(); do not get username form database.


回答1:


You could do something on these lines:

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;
        }
    }        
}

and then you will be able to access it like:

this._identity.GetEmailAdress();



回答2:


You can get the current user in ASP.NET Identity as shown below:

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


For getting custom properties from AspNetUsers table:

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

Hope this helps...



来源:https://stackoverflow.com/questions/42532765/get-current-user-email-in-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!