From where PrincipalContext gets the connected server name?

Viewed 4426

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.

1 Answers

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();
Related