【问题标题】:Unable to cast object of type in System.DirectoryServices.AccountManagement.GroupPrincipal无法在 System.DirectoryServices.AccountManagement.GroupPrincipal 中投射类型的对象
【发布时间】:2012-06-13 12:01:26
【问题描述】:

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

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

【问题讨论】:

  • 这个错误的原因是由于试图从一个未实例化的对象中读取。在服务器上,您需要先创建并填充 PrincipalContext 对象,然后才能从中读取数据。在调试模式下运行时,VS 会自动创建其中一些类型的对象,以便它们可以在调试器中链接到手表等。

标签: c# iis


【解决方案1】:

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

  1. 将身份验证更改为“Windows 身份验证”(how-to)

  2. 不要使用电流,而是分两步进行:(source)

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=))) 搜索过滤器无效
  • @Kurkula 我也看到了同样的情况 - 有什么建议吗?
  • 您必须将Anonymous Authentication 设置为false 并将Windows Authentication 设置为true。如果通过javascript调用端点,则需要withCrendentials = true
  • 我必须使用完全限定名称 HttpContext.Current.User.Identity.Name
【解决方案2】:

我在 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 的标识。

【讨论】:

    【解决方案3】:

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

    根据我的经验,只有“基本”身份验证和 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

    【讨论】:

      猜你喜欢
      • 2012-02-13
      • 2023-03-15
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多