4

我正在使用 ASP.NET MVC 4 和 Windows 身份验证。当我使用 VisualStudio 时,一切正常,但是当我部署我的站点时,会引发异常。

var emailAddress = UserPrincipal.Current.EmailAddress;

抛出:

无法将“System.DirectoryServices.AccountManagement.GroupPrincipal”类型的对象转换为“System.DirectoryServices.AccountManagement.UserPrincipal”类型。

其余的工作正常。用户可以进行身份​​验证,我可以获取用户名等。

编辑:

我在 IIS 上启用了模拟。现在我得到以下异常:

[DirectoryServicesCOMException (0x80072020):发生操作错误。] System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +781 System.DirectoryServices.DirectoryEntry.Bind() +44 System.DirectoryServices.DirectoryEntry.get_AdsObject() +42 System.DirectoryServices.PropertyValueCollection.PopulateList() +29
System.DirectoryServices .PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) +119
System.DirectoryServices.PropertyCollection.get_Item(String propertyName) +163
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() +535649 System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() +51 System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +141 System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() +42 System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate) +27
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType,字符串标识值)+146
System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue) +44
System.DirectoryServices.AccountManagement.UserPrincipal.get_Current() +390 Jericho.MVC.HtmlHelperExtensions.GetUser(HtmlHelper htmlHelper) 在 C:\Development \Jericho\Jericho.MVC\HtmlHelperExtensions.cs:48

我能做些什么?

4

1 回答 1

11

IIS 应用程序池标识设置为NetworkService并使用:

var identityName = HttpContext.Current.User.Identity.Name;
using (HostingEnvironment.Impersonate())
{
    using (var context = new PrincipalContext(ContextType.Domain, "yourDomain", null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer))
    using (var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, identityName))
    {
        emailAddress = userPrincipal.EmailAddress;
        lastname = userPrincipal.Surname;
        firstname = userPrincipal.GivenName;
    }
}
于 2012-06-01T10:53:19.403 回答