I am using Microsoft Graph API SDK to fetch a user from my AD B2C tenant like so:
public static GraphServiceClient GetGraphServiceClient()
{
var clientapp = ConfidentialClientApplicationBuilder
.Create(Globals.ClientId)
.WithTenantId(Globals.TenantId)
.WithClientSecret(Globals.ClientSecret)
.Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(clientapp);
return new GraphServiceClient(authProvider);
}
public static User GetADUserAsyncByEmail(string email)
{
var graphClient = GetGraphServiceClient();
var user = graphClient.Users[email].Request().GetAsync().Result;
return user;
}
But my request just hangs? What am I doing wrong. I am able to use DeleteAsync() fine for example using the same mechanism.
This should work
public static async Task<User> GetADUserAsyncByEmail(string email)
{
var graphClient = GetGraphServiceClient();
var user = await graphClient.Users[email].Request().GetAsync();
return user;
}
Your code is getting hang because your GetADUserAsyncByEmail
does return the User
and in order to return its user it is waiting fot the result of the asyncronous function graphClient.Users[email].Request().GetAsync()
.
var user = await graphClient.Users[email].Request().GetAsync().Result; // Accesing to the Result you are waiting for the `async` completion
In order to avoid that function hang/block your thread, you should make it asyncronous.
Note: This code is similar to the await operator documentation
public static async Task<User> GetADUserAsyncByEmail(string email)
{
var graphClient = GetGraphServiceClient();
var user = await graphClient.Users[email].Request().GetAsync();
return user;
}
So when you call it from your thread it is non-blocking until you want it (you really need its results)
Task<User> fetchingUser = GetADUserAsyncByEmail("jane.doe@gmail.com");
// Do other stuff until you need to access the `User` object
User jane = await fetchingUser; // If if was not already finished, it will wait/block until retrieved.
Console.WriteLine(jane.Address);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.