Asp.net-Identity

IIdentity.Name 與 IIdentity.GetUserName() 擴展方法

  • December 30, 2013

擴展方法在Microsoft.AspNet.Identity. 那麼有什麼區別呢?這兩個什麼時候會返回不同的值?

var idName = User.Identity.Name;
var idGetName = User.Identity.GetUserName();

擴展方法的實現類似於;

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

IIdentity.Name和之間返回值的唯一明顯區別IdentityExtensions.GetUserName()是,GetUserName() 如果基礎 IIdentity 實現不是 aClaimsIdentity,則始終返回 null ,而該Name屬性將返回基礎 IIdentity 實現返回的任何內容。

引用自:https://stackoverflow.com/questions/20830855