【问题标题】:Getting Email address from Active Directory从 Active Directory 获取电子邮件地址
【发布时间】:2013-04-01 13:14:50
【问题描述】:

全部--

我能够检索 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 值。

【问题讨论】:

标签: asp.net vb.net webforms


【解决方案1】:

感谢Davide Piras给我发邮件this link,我找到了合适的解决方案:

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

【讨论】:

    【解决方案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"]); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多