我有一个类,它有三个在Active Directory上具有功能的方法。这是班级:
[Export(typeof(IAuthentication))]
public class Authentication : IAuthentication
{
public bool Authenticate(string domain, string username, string password)
{
try
{
using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain, string.Empty))
{
return principalContext.ValidateCredentials(
username,
password,
ContextOptions.SimpleBind);
}
}
catch (Exception ex)
{
throw ex;
}
}
public UserPrincipal GetUserDetails(string domain, string username)
{
try
{
using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain))
{
return UserPrincipal.FindByIdentity(principalContext, username);
}
}
catch (Exception ex)
{
throw ex;
}
}
public PrincipalSearchResult<Principal> SearchUsers(string domain, string firstName, string lastName, string userName)
{
try
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain))
{
UserPrincipal user = new UserPrincipal(ctx);
user.Enabled = true;
user.Name = firstName + "* " + lastName + "*";
user.SamAccountName = userName + "*";
PrincipalSearcher principalSearcher = new PrincipalSearcher();
principalSearcher.QueryFilter = user;
return principalSearcher.FindAll();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
正如您在class属性中看到的,我正在使用此类库作为MEF插件。在我的asp.net mvc 3应用程序中,我调用这样的方法:
PrincipalSearchResult<Principal> results = _authentication.SearchUsers(
ConfigurationManager.AppSettings["DomainName"],
model.UserSearchCriteria.FirstName,
model.UserSearchCriteria.LastName,
model.UserSearchCriteria.Username);
但是在我打算使用方法的返回值之后,我得到无法访问已处置的对象,对象名称:'PrincipalContext'异常。我知道我正在处理PrincipalContext对象,但如果不这样做,则与Active Directory的连接将保持打开状态。我认为我班级的设计不正确。我怎样才能让它以一种很酷的方式运作?
答案 0 :(得分:1)
我想,当你最终枚举PrincipalSearchResult<T>
的实例时,这个延迟操作就是试图访问已经关闭的上下文。在这种情况下,您可能更好地直接枚举结果并将其作为特定于域的模型返回。即,当时做的工作,而不是通过返回PrincipalSearchResult<T>
推迟它。