我在Azure Active目录中有150个用户,我正是这样得到的:
public List<Generic.UserAAD> GetUsersAAD()
{
ActiveDirectoryClient activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
IPagedCollection<IUser> usersA = activeDirectoryClient.Users.ExecuteAsync().Result;
List<IUser> queryUsers = new List<IUser>();
List<Generic.UserAAD> listUsers = new List<Generic.UserAAD>();
do
{
List<IUser> queryUsersList = usersA.CurrentPage.ToList();
queryUsers.AddRange(queryUsersList);
usersA = usersA.MorePagesAvailable ? usersA = usersA.GetNextPageAsync().Result : null;
} while (usersA != null);
if (queryUsers.Count > 0)
{
listUsers = queryUsers.Select(u => new Generic.UserAAD { DName = u.DisplayName, UName= u.UserPrincipalName }).ToList();
}
return listUsers;
}
这是AuthenticationHelper类:
public class AuthenticationHelper
{
public static async Task<string> AcquireTokenAsyncForApplication()
{
return await GetTokenForApplication().ConfigureAwait(false);
}
public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication()
{
Uri servicePointUri = new Uri(Constantes.graphUrl);
Uri serviceRoot = new Uri(servicePointUri, Constantes.tenantId);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => await AcquireTokenAsyncForApplication().ConfigureAwait(false));
return activeDirectoryClient;
}
public static async Task<string> GetTokenForApplication()
{
AuthenticationContext authContext = new AuthenticationContext(Constantes.authority, false);
ClientCredential clientCred = new ClientCredential(Constantes.clientId, Constantes.appKey);
AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(Constantes.graphUrl,
clientCred).Result;
var token = authenticationResult.AccessToken;
return token;
}
}
所以问题是它在本地运行得很完美但是在Azure Web App上部署它并执行调用GetUsersAAD()方法的服务后,http请求会冻结,几分钟后我就会收到500错误超时。
这是关于AspNet MVC的WebApi2项目。
所以我真的愿意给你任何帮助,谢谢。
答案 0 :(得分:2)
好的,经过阅读和搜索后,我能够使它工作,似乎 .Result 它容易出现死锁,并且不建议在异步方法上使用我也很少使用 async / await / task 调用,所以我的工作方式是:
public async Task<List<Generic.UserAAD>> GetUsersAAD()
{
ActiveDirectoryClient activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
Task<IPagedCollection<IUser>> usersTask = activeDirectoryClient.Users.ExecuteAsync();
IPagedCollection<IUser> usersA = await usersTask;
List<IUser> queryUsers = new List<IUser>();
List<Generic.UserAAD> listUsers = new List<Generic.UserAAD>();
do
{
List<IUser> queryUsersList = usersA.CurrentPage.ToList();
queryUsers.AddRange(queryUsersList);
usersA = usersA.MorePagesAvailable ? await usersA.GetNextPageAsync() : null;
} while (usersA != null);
if (queryUsers.Count > 0)
{
listUsers = queryUsers.Select(u => new Generic.UserAAD { DName = u.DisplayName, UName= u.UserPrincipalName }).ToList();
}
return listUsers;
}
我必须将方法调整为 async Task 以及对它的调用。