簡體   English   中英

如何使用 C# 在 Active Directory 中查找給定的鍵值 (web.config)

[英]How to find given key values (web.config) in Active Directory using C#

我是 Web API 的新手。 我想將我的 PHP 網站與 C# 中的 Web API 連接起來,這將有助於使用 Windows 身份驗證登錄網站。 我在web.config文件中指定了一個key="name"values="DavidR,JohnH" 只有鍵值中提供的名稱才能登錄系統。

public bool Post(string user, string pass, string domain)
{
    DirectoryEntry objDirEntry = new DirectoryEntry("LDAP://" + domain, user, pass);

    try
    {
            DirectorySearcher search = new DirectorySearcher(objDirEntry);
            SearchResult result = search.FindOne();
            string[] name = ConfigurationManager.AppSettings["name"].Split(',');

            foreach (var author in name)
            {
                if (result == null)
                {
                    return false;
                }
                else if(result == name)
                {
                    return true;
                }
            }

            return false;
    }
    catch (Exception)
    {
        return false;
    }
}
<appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    <add key="name" value="DavidR,JohnH"/>
</appSettings>

試試這個代碼:

        public bool Post(string user, string pass, string domain)
    {
        DirectoryEntry objDirEntry = new DirectoryEntry("LDAP://" + domain, user, pass);
        try
        {
            DirectorySearcher search = new DirectorySearcher(objDirEntry);
            SearchResult result = search.FindOne();
            if (result == null)
                return false;
            string[] name = ConfigurationManager.AppSettings["name"].Split(',');
            foreach (var author in name)
            {
                if(author.ToLower() == user.ToLower())
                {
                    return true;
                }
            }
            return false;
        }
        catch (Exception)
        {
            return false;
        }
    }

這段代碼應該有效

您可以像這樣在Linq使用短代碼:

        public bool Post(string user, string pass, string domain)
    {
        DirectoryEntry objDirEntry = new DirectoryEntry("LDAP://" + domain, user, pass);
        try
        {
            DirectorySearcher search = new DirectorySearcher(objDirEntry);
            SearchResult result = search.FindOne();
            if (result == null)
                return false;
            string[] name = ConfigurationManager.AppSettings["name"].Split(',');

            if (name.Any(x => x.ToLower() == user.ToLower()))
                return true;
            return false;
        }
        catch (Exception)
        {
            return false;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM