You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 如何通过LDAP搜索存在mobile属性或属性为指定值的用户

解决方案

你不需要修改原有search方法的核心逻辑,只要调整LDAP查询过滤条件即可实现需求,可选优化方法如下:

场景1:查询所有存在mobile属性的用户

直接将调用时的过滤条件替换为:(&(objectClass=inetOrgPerson)(mobile=*))
其中mobile=*是LDAP的通配符写法,代表匹配所有存在mobile属性的条目,objectClass=inetOrgPerson限定只查询用户对象。
调用示例:

var searchResult = client.search("ou=users,o=freeguests,dc=btechsample,dc=com", "(&(objectClass=inetOrgPerson)(mobile=*))");

场景2:查询mobile属性为指定值的用户

将过滤条件中的mobile=*替换为mobile=指定手机号即可,示例:

// 要查询的目标手机号
string targetMobile = "13800138000";
string ldapFilter = $"(&(objectClass=inetOrgPerson)(mobile={targetMobile}))";
var searchResult = client.search("ou=users,o=freeguests,dc=btechsample,dc=com", ldapFilter);

可选优化:减少不必要的属性传输

如果只需要查询特定属性(比如只需要手机号、用户名),可以修改search方法增加返回属性参数,降低数据传输量:

public List<Dictionary<string, string>> search(string baseDn, string ldapFilter, string[] requiredAttributes = null)
{          
    var result = new List<Dictionary<string, string>>();
    // 未指定返回属性时默认返回所有可读取属性
    var request = requiredAttributes == null 
        ? new SearchRequest(baseDn, ldapFilter, SearchScope.Subtree) 
        : new SearchRequest(baseDn, ldapFilter, SearchScope.Subtree, requiredAttributes);
    if (request != null)
    {
        var response = (SearchResponse)connection.SendRequest(request);
        foreach (SearchResultEntry entry in response.Entries)
        {
            var dic = new Dictionary<string, string>();
            dic["DN"] = entry.DistinguishedName;
            foreach (string attrName in entry.Attributes.AttributeNames)
            {
                dic[attrName] = string.Join(",", entry.Attributes[attrName].GetValues(typeof(string)));
            }
            result.Add(dic);
        }
    }
    return result;
}

优化后调用示例(只返回用户名和手机号):

var searchResult = client.search(
    "ou=users,o=freeguests,dc=btechsample,dc=com", 
    "(&(objectClass=inetOrgPerson)(mobile=*))", 
    new string[]{"cn", "mobile"}
);

注意事项

如果查询的手机号是用户输入的可变值,需要提前转义*、(、)、\、/等LDAP特殊字符,避免出现LDAP注入漏洞。

内容的提问来源于stack exchange,提问作者Kamran Shahid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:15:00