2

全部 -

我能够检索 FullName 值我试图从 Active Directory 中检索电子邮件地址,但在使用 Windows 身份验证的 ASP.Net Web 窗体项目中使用以下代码:

Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
Dim a As String() = wi.Name.Split(New Char() {"\"c}) '' Context.User.Identity.Name.Split('\')

Dim ADEntry As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry(Convert.ToString("WinNT://" + a(0) + "/" + a(1)))
Dim Name As String = ADEntry.Properties("FullName").Value.ToString()
Dim Email As String = ADEntry.Properties("mail").Value.ToString()

当我到达尝试检索电子邮件地址的代码行时,我得到一个“对象引用未设置为对象实例”。错误。我曾尝试使用电子邮件地址、电子邮件。我认为问题在于我只是使用了错误的关键字。我能够检索 FullName 值。

4

2 回答 2

6

感谢向我发送此链接的Davide Piras,我找到了一个合适的解决方案:

Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
Dim a As String() = wi.Name.Split(New Char() {"\"c}) '' Context.User.Identity.Name.Split('\')

Dim dc As PrincipalContext = New PrincipalContext(ContextType.Domain, "DomainName")
Dim adUser As UserPrincipal = UserPrincipal.FindByIdentity(dc, a(1))
Dim Email As String = adUser.EmailAddress
于 2013-04-09T22:12:29.663 回答
2

此代码适用于我.. 参考System.DirectoryServices.AccountManagement

   static string GetADUserEmailAddress(string username)
    {
        using (var pctx = new PrincipalContext(ContextType.Domain))
        {
            using (UserPrincipal up = UserPrincipal.FindByIdentity(pctx, username))
            {
                return up != null && !String.IsNullOrEmpty(up.EmailAddress) ? up.EmailAddress : string.Empty;
            }
        }
    }

使用它:

lblEmail.Text = GetADUserEmailAddress(Request.ServerVariables["AUTH_USER"]); 
于 2013-12-03T07:05:19.230 回答