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

时间:2012-06-13 12:01:26

标签: c# iis

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

Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal'
           to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.

3 个答案:

答案 0 :(得分:27)

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

  1. 将身份验证更改为" Windows身份验证" (how-to

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

  3. PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

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

    为了最终获得名称(或任何其他信息),我使用了user.DisplayName

答案 1 :(得分:6)

在Windows 7上的IIS 7下运行时,我看到了这个异常。

  

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

这是not a real user account,它部分解释了正在发生的事情,尽管恕我直言UserPrincipal.Current应该更优雅地处理这种情况。

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

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

要解决此问题,请使用System.Security.Principal.WindowsIdentity.GetCurrent()获取IIS AppPool的身份。

答案 2 :(得分:2)

这里的问题是UserPrincipal.Current属性将尝试访问当前线程的上下文。但是,如果没有ASP.NET模拟,则表示标识将是应用程序池的已配置标识。即使使用ASP.NET模拟,它也必须以某种方式访问​​Active Directory,因此需要对域控制器进行身份验证。如果IIS中选定的身份验证方法没有提供,则可能出现类似错误。

根据我的经验,只有" BASIC"身份验证和100%正确实施的" KERBEROS"将工作。请记住,Kerberos与应用程序池和SPN的处理方式并不完全兼容,并且可能会失败。 NTLM - 这是IIS中Windows身份验证的后备 - 由于服务器上缺少密码而无法正常工作。

关于HTTP / Kerberos问题的一个很好的解读是:http://blogs.msdn.com/b/friis/archive/2009/12/31/things-to-check-when-kerberos-authentication-fails-using-iis-ie.aspx