0

在 Asp.Net MVC 4 windows 身份验证模式下,是否可以获得有关当前用户的更多信息(如姓名和家庭)?

4

1 回答 1

0

获取用户名后,您可以使用 Active Directory API 获取用户的其他属性。例如,您可以使用以下代码:

Using System.DirectoryServices;

...

DirectoryEntry entry = new DirectoryEntry("LDAP://DomainName");
DirectorySearcher dSearch = new DirectorySearcher(entry);
dSearch.PropertiesToLoad.Add("displayName");
dSearch.PropertiesToLoad.Add("cn");
dSearch.PropertiesToLoad.Add("department");
dSearch.Filter = "(&(objectClass=user)(l=" + username + "))";
foreach (SearchResult result in searcher.FindAll())
        {
            // Login Name
            Console.WriteLine(GetProperty(result, "cn"));
            // Display Name
            Console.WriteLine(GetProperty(result, "displayName"));
            // Department
            Console.WriteLine(GetProperty(result, "department"));
        }

这可以是 GetProperty 方法:

private string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

和 propertyName 可以是如下值:

  • 登录名:“cn”
  • 名字:“givenName”
  • 中间首字母:“首字母”
  • 姓氏:“sn”
  • 地址:“homePostalAddress”
  • ...
于 2013-04-07T20:29:45.183 回答