Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get current user email in Identity

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.

like image 480
Soheil Alizadeh Avatar asked Mar 01 '17 13:03

Soheil Alizadeh


1 Answers

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();
like image 50
Jinish Avatar answered Oct 31 '22 12:10

Jinish