9

为什么下面的代码在我运行我的 Web 应用程序 localhost 时可以正常工作,但在我将其安装到 IIS 服务器时却不行?

using (HostingEnvironment.Impersonate())
{
    UserPrincipal activeUser = UserPrincipal.Current;
    String activeUserSid = activeUser.Sid.ToString();
    String activeUserUPN = activeUser.UserPrincipalName;
}

请不要建议我坚持,HttpContext.Current.User因为它不提供对 SID 或 UPN 的访问,而无需额外调用 Active Directory。

Web 应用程序将由来自三个独立域的 Windows 身份验证用户使用,Web 服务器托管在第四个域中。应用程序池配置为在NetworkService身份下运行,并且 Web 应用配置将身份模拟设置为 true。

在 IIS 上运行时的错误消息是:

Page_Load() 中的错误:UserPrincipal.Current。
System.InvalidCastException:无法将“System.DirectoryServices.AccountManagement.GroupPrincipal”类型的对象转换为“System.DirectoryServices.AccountManagement.UserPrincipal”类型。
在 System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)
在 System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()
在 webapp.Details.Default.Page_Load(Object sender, EventArgs e)

编辑:尝试了以下两种方法,不幸的是得到了同样的错误。

UserPrincipal userPrincipal = UserPrincipal.Current;
Response.Write(userPrincipal.Name);
Principal userOrGroup = UserPrincipal.Current;
Response.Write(userOrGroup.Name);
4

3 回答 3

4

我在部署 UserPrincipal.Current 时遇到了很多问题,但仍然不完全明白为什么。

我最终最终使用了 PrincipalSearcher,并创建了以下函数来完成我认为 UserPrincipal.Current 正在做的事情。

private UserPrincipal GetActiveDirectoryUser(string userName)
{
    using(var ctx = new PrincipalContext(ContextType.Domain))
    using(var user = new UserPrincipal(ctx) { SamAccountName = userName})
    using(var searcher = new PrincipalSearcher(user))
    {
        return searcher.FindOne() as UserPrincipal;
    }
}

我将 System.Web.HttpContext.Current.User.Identity.Name 作为用户名传递给该方法。

于 2014-01-13T19:32:02.743 回答
2

似乎需要一些其他方法来确定用户。
这里来自 msdn 的属性描述:
“获取代表当前运行线程的用户的用户主体对象。”
因此,UserPrincipal.Current 返回运行 IIS 的用户。

http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal.aspx

于 2012-06-21T14:35:46.433 回答
0

是的,这是因为由于多个 using 语句,您正在处理返回的 UserPrincipal 对象。从 using 语句中删除 'ctx',然后调用者负责处理返回的对象。

于 2019-01-23T11:41:11.360 回答