Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIdentity.Name versus IIdentity.GetUserName() extension method

The extension method is in Microsoft.AspNet.Identity. So what's the difference? When will these 2 return different values?

var idName = User.Identity.Name;
var idGetName = User.Identity.GetUserName();
like image 445
danludwig Avatar asked Dec 29 '13 22:12

danludwig


1 Answers

The implementation of the extension method is something like;

public static string GetUserName(this IIdentity identity)
{
    if (identity == null)
    {
        throw new ArgumentNullException("identity");
    }
    ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
    if (claimsIdentity == null)
    {
        return null;
    }
    return claimsIdentity.FindFirstValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name");
}

The only apparent difference in return value between IIdentity.Name and IdentityExtensions.GetUserName() is that GetUserName() always returns null if the underlying IIdentity implementation is not a ClaimsIdentity, while the Name property will return whatever the underlying IIdentity implementation returns.

like image 60
Joachim Isaksson Avatar answered Nov 03 '22 06:11

Joachim Isaksson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!