How to specify domain controller using PrincipalContext?

Jaime Stuardo 71 Reputation points
2022-10-06T22:51:16.367+00:00

Hello,

I am developing an MVC 5 application that needs to implement active directory authentication.

I am stuck at this instruction:

PrincipalContext principalContext = new PrincipalContext(authenticationType,   
                Properties.Settings.Default.AD_NombreServidor,   
                $"OU={Properties.Settings.Default.AD_OrganizationUnit}, DC={Properties.Settings.Default.AD_Dominio}, DC={Properties.Settings.Default.AD_Sufijo}");  

his does not work, so I am wondering if I am doing the right way.

Properties.Settings.Default.AD_NombreServidor is the domain controller (name or IP).

Is it right how I am calling that function? if It isn't, how is it the right way?

Thanks
Jaime

Windows for business Windows Client for IT Pros Directory services Active Directory
Developer technologies ASP.NET Other
Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2022-10-07T02:21:54.51+00:00

    Hi @Jaime Stuardo ,
    I suggest you look at the documentation for the PrincipalContext constructor, it should be clear:
    https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.principalcontext.-ctor?view=dotnet-plat-ext-6.0#system-directoryservices-accountmanagement-principalcontext-ctor(system-directoryservices-accountmanagement-contexttype-system-string-system-string)

    public PrincipalContext(ContextType contextType, string name, string container)  
    

    So you basically need:

    • your context type(Connect to domain (using ContextType.Domain))
    • the domain name(The name part of this principal context can be set to an IP address of a domain controller.)
    • optionally a container

    For example:

    new PrincipalContext(ContextType.Domain, "xyz.mycorp.com:****", "DC=mycorp,DC=com");  
    new PrincipalContext(ContextType.Domain, "mycompany.local", "OU=Marketing,OU=Operations,OU=Applications,DC=mycompany,DC=local");  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.