Jesus
Jesus

Reputation: 475

Get claim email address

I want to access my email address via Claim inside Identity

I tried accessing as:

var email = User.Identity.GetClaimsByType("emailaddress").ToString();
var email = User.Identity.GetClaimsByType("email").ToString();
var email = User.Identity.GetClaimsByType("Email").ToString();

But none of these works, it always return null, how can I get it?

The claim is:

{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress: [email protected]}

Upvotes: 3

Views: 3440

Answers (1)

Nathan Foss
Nathan Foss

Reputation: 680

C# offers a Claim Types Enum to represent the claim type url. The code would look like this:

var email = User.Identity.GetClaimsByType(ClaimTypes.Email)
    .Select(x => x.Value).FirstOrDefault().ToString();

If you support custom Claim Types in your identity, you could use LINQ.

var claimValue = User.Identity.Claims
    .FirstOrDefault(claim => claim.Type.Contains(<my custom claim type>));

Upvotes: 7

Related Questions