2009-07-09 87 views
16

我不是一個.NET開發人員,我有一種感覺,這將是微不足道的人誰是:獲取UPN或電子郵件登錄的用戶在.NET Web應用程序

我有一個C#的Web應用程序這使得登錄用戶的用戶憑證的用戶成爲可能。目前,它使用了來自

System.Security.Principal.WindowsIdentity.GetCurrent().User.Value 

我需要得到的,而不是SID無論是用戶UPN賬號或電子郵件地址(如Active Directory中定義)的SID。 GetCurrent()返回一個WindowsIdentity類型的對象;尋找在的WindowsIdentity成員的詳細信息:

MSDN: WindowsIdentity Members

我看不到任何東西,看起來像它會給我無論是UPN或電子郵件在那裏。我怎樣才能提取這些信息來使用,或者通過將SID提供給其他函數或者首先調用不同的東西。

回答

35

同時(.NET 3.5),這是一個一個班輪:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.EmailAddress 

的電子郵件,或

System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName 

爲UPN。

1

嘗試:

System.Security.Principal.WindowsIdentity.GetCurrent().Name 
+1

該文檔顯示「獲取用戶的Windows登錄名」。 - 這會返回NT風格的名稱還是UPN風格的名稱?我知道微軟在很多年前說過UPN將會是識別用戶的新方式,但根據我的經驗,幾乎所有的功能都可以使用NT Style憑據 - 用戶可以使用UPN或NT Style logoins登錄到該網站,所以我不能依靠使用與用戶相同的表單。 – DrStalker 2009-07-09 05:41:09

+0

剛剛做了一個快速測試和System.Security.Principal.WindowsIdentity.GetCurrent()。名稱 從中返回DOMAIN \ username – DrStalker 2009-07-09 06:22:22

2

要使用你需要做的是這樣的(沒有經過測試的代碼)的目錄搜索查詢Active Directory:

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; 
    string ldapPath = "LDAP://domain.company.com"; 

    public string GetEmail(string userName, string ldapPath) 
    { 
     using (DirectoryEntry root = new DirectoryEntry(ldapPath)) 
     { 
      DirectorySearcher searcher = new DirectorySearcher(root); 
      searcher.Filter = string.Format(@"(&(sAMAccountName={0}))", userName); 
      searcher.PropertiesToLoad = "mail"; 

      SearchResult result = searcher.FindOne(); 

      if (result != null) 
      { 
       PropertyValueCollection property = result.Properties["mail"]; 
       return (string)property.Value; 
      } 
      else 
      { 
       // something bad happened 
      } 
     } 
    } 
相關問題