全部 -
我能够恢复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()
当我到达我尝试检索电子邮件地址的代码行时,我得到一个“对象引用未设置为对象的实例”。错误。我尝试过使用EmailAddress,电子邮件。我认为问题是我只是使用了错误的关键字。我能够检索FullName值。
答案 0 :(得分:6)
感谢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
答案 1 :(得分: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"]);