C#PrincipalContext错误“服务器名称不能包含空格字符”

我收到以下错误

使用PrincipalContext获取域用户的信息时,“服务器名称不能包含空格字符”。

此代码在我的计算机上本地工作,但在我在Intranet Web服务器上加载时会崩溃。

//GET CURRENT USER String winUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name; string[] domainUsername = winUser.Split(Convert.ToChar(@"\")); // set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainUsername[0]); // find a user UserPrincipal user = UserPrincipal.FindByIdentity(ctx, domainUsername[1]); return user; 

发生这种情况是因为如果没有指定容器,则主体上下文类将通过绑定到内置CN = Users容器来创建System.DirectoryServices.DirectoryEntry对象,以开始搜索用户。 系统,

考虑此链接上的示例以及exception页面 。

对我来说,这是因为PrincipalContext的设置低于此。

在将应用程序池的标识从ApplicationPoolIdenity更改为LocalSystem之后,它得到了解决。

它不是一个真正的解决方案,但可以帮助某人。

 PrincipalContext pc = new PrincipalContext((Environment.UserDomainName == Environment.MachineName ? ContextType.Machine : ContextType.Domain), Environment.UserDomainName);