I am trying to get the Azure AD directory object name from object Id. Currently, I have the below code which uses the Graph Client library. However, it involves atleast 2 calls to Graph API. Is it possible to optimize it to 1 call?
string objectName;
ActiveDirectoryClient client = GetActiveDirectoryClient();
IDirectoryObject dirObj = await client.DirectoryObjects.GetByObjectId(objectId).ExecuteAsync();
// IDirectoryObject does not have a Name property so having to check the object type and make a second call
if (dirObj.ObjectType == "User")
{
IUser user = await client.Users.GetByObjectId(objectId).ExecuteAsync();
objectName = user.UserPrincipalName;
}
else if (dirObj.ObjectType == "ServicePrincipal")
{
IServicePrincipal principal = await client.ServicePrincipals.GetByObjectId(objectId).ExecuteAsync();
objectName = principal.DisplayName;
}
string objectName;
ActiveDirectoryClient client = GetActiveDirectoryClient();
IDirectoryObject dirObj = await client.DirectoryObjects.GetByObjectId(objectId).ExecuteAsync();
// IDirectoryObject does not have a Name property so having to check the object type and make a second call
if (dirObj.ObjectType == "User")
{
IUser user = await client.Users.GetByObjectId(objectId).ExecuteAsync();
objectName = user.UserPrincipalName;
}
else if (dirObj.ObjectType == "ServicePrincipal")
{
IServicePrincipal principal = await client.ServicePrincipals.GetByObjectId(objectId).ExecuteAsync();
objectName = principal.DisplayName;
}