C# 如何在我的模型类中编写验证来检查用户是否在Active Directory中

C# 如何在我的模型类中编写验证来检查用户是否在Active Directory中,c#,asp.net-mvc,active-directory,C#,Asp.net Mvc,Active Directory,我有一个UserGroup表,它存储GroupID和关联的用户名。当前用户存在于active directory中,因此我没有用户表。 但在将任何用户分配到UserGroup表之前,我想检查该用户是否已在Active Directory中定义。因此,我发现在我的UserGroup模型对象中编写验证对象是一种很好的方法,因此我在我的UserGroup部分类中编写了以下内容:- List<DomainContext> results = new List<DomainContext

我有一个UserGroup表,它存储GroupID和关联的用户名。当前用户存在于active directory中,因此我没有用户表。 但在将任何用户分配到UserGroup表之前,我想检查该用户是否已在Active Directory中定义。因此,我发现在我的UserGroup模型对象中编写验证对象是一种很好的方法,因此我在我的UserGroup部分类中编写了以下内容:-

List<DomainContext> results = new List<DomainContext>();
using (var context = new PrincipalContext(ContextType.Domain, "WIN-SPDEV"))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
   var searchResults = searcher.FindAll();
   foreach (Principal p in searchResults)
   {
     //not sure what to write here !!!
}}
yield return new ValidationResult("UserName does not exsists.");}
列表结果=新列表();
使用(var context=newprincipalcontext(ContextType.Domain,“WIN-SPDEV”))
使用(var searcher=newprincipalsearcher(newuserprincipal(context)))
{
var searchResults=searcher.FindAll();
foreach(搜索结果中的负责人p)
{
//不知道在这里写什么!!!
}}
返回新的ValidationResult(“用户名不存在”);}
但我不知道如何实现唯一性检查

请尝试以下代码:

var searchResults = searcher.FindAll();
foreach (Principal p in searchResults)
{
  if(p.SamAccountName == User.Identity.Name)
  {
      //your in!
  }
}
尝试:


我不想比较当前登录用户!!!。我正在使用一个intranet web应用程序,因此当前登录用户将始终在广告中!!!非常感谢,它工作得很好,但是在模型类内调用Active Directory是一种不好的做法?您可以创建一个自定义验证属性,并在其中调用Active Directory。
using (var context = new PrincipalContext(ContextType.Domain, "WIN-SPDEV"))
{
    UserPrincipal user = UserPrincipal.FindByIdentity(context, searchedUserName);
    if (user != null)
    {
        //user found
    }
}