I am building an Intranet application and I am using Windows authentication. I have this setup and working and I am able to see the current users username via @Context.User.Identity.Name
I would like to query the Active Directory to retrieve the Display Name, email address, etc.
I have looked at System.DirectoryServices.AccountManagement and from this have created a basic example. I am not clear though on how to display this information throughout my application.
What I have so far is as follows:
public class searchAD
{
// Establish Domain Context
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain);
public searchAD()
{
// find the user
UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, HttpContext.Current.User.Identity.Name);
if (user != null)
{
var userGuid = user.Guid;
var DisplayName = user.DisplayName;
var GivenName = user.GivenName;
var EmailAddress = user.EmailAddress;
}
}
}
I am assuming I need to create a ViewModel like so?
public class domainContext
{
public Nullable<Guid> userGuid { get; set; }
public string DisplayName { get; set; }
public string GivenName { get; set; }
public string EmailAddress { get; set; }
}
I want to be able to access this information in various sections of the application.
I am not getting any errors just seem to be missing something that ties all this together.
You’re missing the windows identity part. Also, remember to dispose of any AD objects you are using:
The best thing to do so you can access this everyone within your application is to create a class called ‘BaseController’ which all your other controllers inherit from, and put this code on there (ideally as a property called DomainContext).
To use this on all over your application, you can also add a method on the base controller to add this information to the ViewData:
Then you can access this on any of your views rendered from this any inheriting controller by using:
Of course you’ll run into problems with nulls, but you could handle that in your GetUserDetails method with some sort of dummy DomainContext.
This is just one way of doing it, alternatively you could create a base view model that all your view models inherit from and access them directly in the view, but I’ve found this way to be simpler as you don’t add any complexity to your view models.