C# C System.DirectoryServices.AccountManagement-UserPrincipal.FindByIdentity为某些用户返回NULL

C# C System.DirectoryServices.AccountManagement-UserPrincipal.FindByIdentity为某些用户返回NULL,c#,asp.net,asp.net-mvc,active-directory,C#,Asp.net,Asp.net Mvc,Active Directory,我目前正在使用一种方法从广告中获取当前登录用户的GivenName和姓氏。所有访问此网站的用户都将是广告中的内部用户 对于某些用户来说,这是可行的,而对于其他用户来说,在尝试查找ByIdentity时,UserPrincipal似乎返回NULL。这是你的事吗?我没有指定要查找的OU,我只是希望它通过他们的登录名查找当前登录的用户,并拉取他们的名字/姓氏,无论他们在广告结构中的什么位置 下面是我的方法的代码。。。它接受包含当前用户的user.Identity.Name的参数 public stat

我目前正在使用一种方法从广告中获取当前登录用户的GivenName和姓氏。所有访问此网站的用户都将是广告中的内部用户

对于某些用户来说,这是可行的,而对于其他用户来说,在尝试查找ByIdentity时,UserPrincipal似乎返回NULL。这是你的事吗?我没有指定要查找的OU,我只是希望它通过他们的登录名查找当前登录的用户,并拉取他们的名字/姓氏,无论他们在广告结构中的什么位置

下面是我的方法的代码。。。它接受包含当前用户的user.Identity.Name的参数

public static string GetFullName(string userIdentityName)
{            
    using (var context = new PrincipalContext(ContextType.Domain))
    {
        using (UserPrincipal principal = UserPrincipal.FindByIdentity(context, userIdentityName))
        {
            return principal != null ? principal.GivenName + " " + principal.Surname : "User Not Found";
        }
    }
}
我还在页面上输出User.Identity.Name,这对每个人都有效,因此我知道传递到方法中的参数已填充

奇怪的是,我可以硬编码一个通常返回null的用户标识名,并且即使完全相同的内容正在通过param传递,代码仍然可以工作。比如:

public static string GetFullName(string userIdentityName)
{
    var username = "DOMAIN\\username";

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        using (UserPrincipal principal = UserPrincipal.FindByIdentity(context, username))
        {
            return principal != null ? principal.GivenName + " " + principal.Surname : "User Not Found";
        }
    }
}

我不明白。。。任何帮助都将不胜感激!谢谢

如果只搜索用户名而不搜索'domain\'部分怎么办?另外,请尝试将标识类型传递给FindByIdentity方法:FindByIdentitycontext、IdentityType.SamAccountName、UserIdentityName上述方法之一有效。不幸的是,我在web.config中添加了模拟,现在一切都很顺利。非常感谢。