无法在System.DirectoryServices.AccountManagement.GroupPrincipal中转换类型的对象

Sun*_*ari 19 c# iis

我正在UserPrincipal.Current.ToString()域中使用方法来获取具有有效域的域用户当前记录.但当我在一个字符串中显示它时,它在IIS服务器中托管时给出错误:

Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal'
           to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.
Run Code Online (Sandbox Code Playgroud)

小智 30

我有同样的问题.它在我的本地计算机上运行良好,但在将其部署到服务器上的IIS时失败了.最后我不得不改变两件事来使其发挥作用:

  1. 将身份验证更改为"Windows身份验证"(操作方法)

  2. 而不是使用当前,分两步执行:( )

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

UserPrincipal user = UserPrincipal.FindByIdentity(ctx, User.Identity.Name);

最后得到了名字(或任何其他信息),我用过user.DisplayName.

  • 这对我抛出错误(&(objectCategory = user)(objectClass = user)(|(userPrincipalName =)(distinguishedName =)(name =)))搜索过滤器无效.描述:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息.异常详细信息:System.ArgumentException:(&(objectCategory = user)(objectClass = user)(|(userPrincipalName =)(distinguishedName =)(name =)))搜索过滤器无效 (4认同)
  • 您必须将“匿名身份验证”设置为 false,将“Windows 身份验证”设置为 true。如果通过javascript调用端点,则需要`withCrendentials = true` (2认同)

Joe*_*Joe 6

在Windows 7上的IIS 7下运行时,我看到了此异常.

System.Security.Principal.WindowsIdentity.GetCurrent().Name返回"IIS APPPOOL\ASP.NET v4.0".

不是真正的用户帐户,这部分解释了正在发生的事情,尽管恕我直言UserPrincipal.Current应该更优雅地处理这种情况.

我认为这是一个错误,并在Connect上创建了一个错误:

http://connect.microsoft.com/VisualStudio/feedback/details/748790/userprincipal-current-throws-invalidcastexception

作为解决方法,用于System.Security.Principal.WindowsIdentity.GetCurrent()获取IIS AppPool的标识.