简体   繁体   中英

From where PrincipalContext gets the connected server name?

I have a web application with windows authentication. When I debug the line

var domainContext = new PrincipalContext(ContextType.Domain, "abc");

where "abc" is domain name.

I can see the connected server as domain controller name. I would like to know from where it is getting the DC name.

Actually, the issue is, even though a particular DC is demoted and new DC is added, our application always pointing to the same demoted DC and throws error when we try to get groups of the user using the below lines.

var user = UserPrincipal.FindByIdentity(domainContext, "username");
var groups = user.GetGroups();

[ActiveDirectoryServerDownException: The server is not operational.

Name: "DomainController.Domain.com"

]

System.DirectoryServices.ActiveDirectory.PropertyManager.GetPropertyValue(DirectoryContext context, DirectoryEntry directoryEntry, String propertyName) +510

System.DirectoryServices.ActiveDirectory.DirectoryEntryManager.ExpandWellKnownDN(WellKnownDN dn) +239

System.DirectoryServices.ActiveDirectory.DomainController.get_Domain() +71

System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOf(Principal p) +839

System.DirectoryServices.AccountManagement.Principal.GetGroups() +32

Do I need to clear IIS cache or some other cache? I have restarted the IIS too.

You can retrieve the DC name programmatically if your server belongs to domain controller .

    using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain))
    {
        server = context.ConnectedServer; 
        //Output : dc.example.com
        var formatted = server.Split('.').Select(s => String.Format("DC={0}", s));
        joined = String.Join(",", formatted); 
        // Output DC=dc,DC=example,DC=com
    }

If the server isn't a part of the domain controller . You can retrieve it by using credentials like this;

        System.DirectoryServices.ActiveDirectory.DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, "domainName", "domainUser", "Password");
        var domain = ActiveDirectory.Domain.GetDomain(domainContext);
        var controller = domain.FindDomainController();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM