IIdentity.Name与IIdentity.GetUserName()扩展方法

dan*_*wig 8 asp.net-identity

扩展方法是在Microsoft.AspNet.Identity.那有什么区别?这些2什么时候会返回不同的值?

var idName = User.Identity.Name;
var idGetName = User.Identity.GetUserName();
Run Code Online (Sandbox Code Playgroud)

Joa*_*son 11

扩展方法的实现是这样的;

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");
}
Run Code Online (Sandbox Code Playgroud)

在与返回值的唯一明显的区别IIdentity.Name,并IdentityExtensions.GetUserName()是,GetUserName() 如果底层的IIdentity实现是不是总是返回nullClaimsIdentity,而Name属性将返回任何潜在的IIdentity实现返回.