扩展UserPrincipal只返回一个空字符串

本文关键字:一个 字符串 UserPrincipal 返回 扩展 | 更新日期: 2023-09-27 18:11:54

我试图找到一种方法来从默认情况下不在UserPrincipal对象中的活动目录用户获得一些属性。在寻找答案的过程中,我遇到了这个问题。我相信@marc_s的答案是对的,至少它非常有用。因为它很有用,我创建了一个UserPrincipalEx类,并做了@marc_s在他的回答中建议的一切。类本身似乎被正确定义,除了我的扩展属性,在这种情况下,title总是返回一个空字符串。我在AD中仔细检查了属性被称为title,所以我应该抓住正确的属性,我只是没有得到任何内容。

@marc_s还提到类是骨架,但如果这就是为什么我不能让它工作,我还需要添加什么?

我在它们自己的.csUserPrincipalEx.cs中定义了这两个类,并且我在该文件中定义了UserPrincipalExSearchFilterUserPrincipalEx类。当我在代码中创建对象时,它总是返回一个空字符串。

UserPrincipalEx user = new UserPrincipalEx(principal.Context);
if (user == null) return false;
return user.Title == "A value other than empty" | (user.Title == "" || user.Title == null);

我还需要做些什么来从AD中获取title的值?

更新:

如果我遵循title属性的检索,UserPrincipalEx总是说它是空的,这继续让我觉得我做错了UserPrincipalEx.cs

[DirectoryProperty("title")]
public string Title
{
    get
    {
        if (ExtensionGet("title").Length != 1)
            return string.Empty;
        return (string)ExtensionGet("title")[0];
    }
    set { ExtensionSet("title", value); }
}

它总是命中return string.Empty;并且像行所说的那样,返回一个空字符串

更新2:

从我可以告诉它没有关系的扩展属性,你正在寻找UserPrincipalEx将始终返回一个null,使字符串为空。

扩展UserPrincipal只返回一个空字符串

没有使用扩展的UserPrincipal,我最终只是使用DictionaryEntry来查找值并比较它,而不是像这样。

UserPrincipal user = new UserPrincipal(principal.Context);
if (user == null) return false;
DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
string title = "";
if (directoryEntry.Properties.Contains("title"))
{
    title = directoryEntry.Properties["title"].Value.ToString();
}
return title == "Comparison Value" | (title == "" || title == null);