为什么下面的代码在我运行我的 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);