I am trying to connect with active directory using principle context. i have tried with below code.
using (var context = new PrincipalContext(ContextType.Domain,
ConfigurationManager.AppSettings["DomainName"].ToString()))
{
try
{
writeLog("Before:" + isCheckUserName);
writeLog("Context name:" + context.Name);
var user = UserPrincipal.FindByIdentity(context, GetCurrentWindowsLogin());
writeLog("GetCurrent:" + GetCurrentWindowsLogin());
writeLog("After:" + user.EmployeeId);
if (user != null) {
StaffName = user.DisplayName;
StaffID = user.EmployeeId;
}
}
catch (Exception ex)
{
writeLog($"Second try: Error - {ex.Message} Inner Exception: {ex.InnerException.Message}");
}
}
this code is working fine on client's local machine but after upload on client's server it will throw a null reference exception.
any idea. thanks.
I have solved these by my self. I have add two more parameters in below PrincipleContext Constructor. That are Active Directory Domain Username and Password.
using (var context = new PrincipalContext(ContextType.Domain,
ConfigurationManager.AppSettings["DomainName"].ToString(),
ConfigurationManager.AppSettings["ADUserName"].ToString(),
ConfigurationManager.AppSettings["ADPassword"].ToString()))
{
try
{
writeLog("Before:" + isCheckUserName);
writeLog("Context name:" + context.Name);
var user = UserPrincipal.FindByIdentity(context, GetCurrentWindowsLogin());
writeLog("GetCurrent:" + GetCurrentWindowsLogin());
writeLog("After:" + user.EmployeeId);
if (user != null)
{
StaffName = user.DisplayName;
StaffID = user.EmployeeId;
}
}
catch (Exception ex)
{
writeLog($"Second try: Error - {ex.Message} Inner Exception: {ex.InnerException.Message}");
}
}
and changing in IIS Authorization. Set Anonymous Authentication to "Disable", and Set ASP.NET Impersonation to "Enable".