在.NET Web应用程序中获取登录用户的UPN或电子邮件

我不是.NET开发人员,我觉得这对于以下人员来说是微不足道的:

我有一个C#Web应用程序,它使用户获得登录用户的用户凭据。 目前它使用来自的SID

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

我需要获取用户UPN登录或电子邮件地址(在活动目录中定义)而不是SID。 GetCurrent()返回一个WindowsIdentity类型的对象; 查看WindowsIdentity成员的详细信息:

MSDN:WindowsIdentity成员

我看不到任何看起来会给我UPN或电子邮件的内容。 如何通过将SID提供给其他function或首先调用不同的function来提取要使用的信息。

同时(.NET 3.5)这是一个单行:

 System.DirectoryServices.AccountManagement.UserPrincipal.Current.EmailAddress 

对于电子邮件,或

 System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName 

对于UPN。

要使用目录搜索器查询活动目录,您需要执行以下操作(完全未经测试的代码):

  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 } } } 

尝试:

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