0

我想创建一个新的操作方法,调用它时将返回所有 Active Directory 用户名。asp.net mvc 应用程序和 Active Directory 在同一个域中(并且当前在同一个开发机器中)。

所以我定义了以下动作方法:-

public ViewResult Details()
        {
 var c = repository.GetUserDetails3();
return View("Details2",c); }

以及以下存储库方法:-

public DirectoryEntry GetUserDetails3()
{   
     DirectoryEntry de = new DirectoryEntry();

     using (var context = new PrincipalContext(ContextType.Domain, "WIN-SPDEV.com"))
     {
         using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
         {
             foreach (var result in searcher.FindAll())
             {
                 de = result.GetUnderlyingObject() as DirectoryEntry; 
             }
         }
     }
     return de; 
}

和以下模型类:-

public class DirectoryUser
    {public Nullable<Guid> Guid { get; set; }
        public string Name { get; set; }
        public string Username { get; set; }
}}

在我看来:-

@model IEnumerable<TMS.Models.DirectoryUser>

@{
    ViewBag.Title = "Details2";
}

<h2>Details2</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Guid)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Username)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Guid)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Username)
        </td>

但是当我调用操作方法时,出现以下错误:-

参数字典包含不可为空类型的参数“id”的空条目

传入字典的模型项的类型为“System.DirectoryServices.DirectoryEntry”,但此字典需要“System.Collections.Generic.IEnumerable`1[TMS.Models.DirectoryUser]”类型的模型项。

4

1 回答 1

2

我不明白你为什么要把新东西PrincipalContext和旧DirectoryEntry东西混在一起。没有任何意义......

另外 - 您正在搜索所有用户,但最后,您只返回一个DirectoryEntry- 为什么?!?

如果您使用的是新的PrincipalContext- 然后使用UserPrincipal- 它包含关于用户的漂亮且易于使用的属性 - 比旧的东西更容易使用和使用DirectoryEntry......

public List<UserPrincipal> GetAllUsersDetails()
{   
    using (var context = new PrincipalContext(ContextType.Domain, "WIN-SPDEV.com"))
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
       var searchResults = searcher.FindAll();

       List<UserPrincipal> results = new List<UserPrincipal>();

       foreach(Principal p in searchResults)
       {
           results.Add(p as UserPrincipal);
       }
    }
}

该类UserPrincipal具有非常好的属性,例如GivenName(名字)Surname等等 - 易于使用,强类型属性。使用它们!

在此处阅读有关这些新课程以及如何使用它们的所有信息:

于 2013-07-14T17:24:34.883 回答