为什么下面的代码在我运行 Web 应用程序 localhost 时可以正常工作,但在将其安装到 IIS 服务器时却不能正常工作?
using (HostingEnvironment.Impersonate())
{
UserPrincipal activeUser = UserPrincipal.Current;
String activeUserSid = activeUser.Sid.ToString();
String activeUserUPN = activeUser.UserPrincipalName;
}
请不要建议我坚持使用 HttpContext.Current.User
,因为它无法在不额外调用 Active Directory 的情况下提供对 SID 或 UPN 的访问。
Web 应用程序将由来自三个不同域的 Windows 身份验证用户使用,Web 服务器托管在第四个域中。应用程序池配置为在 NetworkService
身份下运行,并且 Web 应用配置将身份模拟设置为 true。
在IIS上运行时的错误信息是:
Error in Page_Load(): UserPrincipal.Current.
System.InvalidCastException: Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)
at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()
at 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);
最佳答案
我在部署 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 作为用户名传递到该方法中。
关于asp.net - System.DirectoryServices.AccountManagement.UserPrincipal - localhost 但不是 iis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11138373/