2 回答
TA贡献1946条经验 获得超4个赞
所以这里发生了一些事情。
第一个也是最明显的问题是您的代码连续三次从图表请求相同的用户记录。您拨打的每个电话都会GetDirectManagerForUser下载整个用户配置文件。你想避免这样做:
var manager = await graphHelper.GetManagerForCurrentUser(userIdToCheck);
var allUsersConnectedToCurrentManagerDisplayName = manager.DisplayName;
var allUsersConnectedToCurrentManagerEmail = manager.UserPrincipalName;
var allUsersConnectedToCurrentManagerId = manager.Id;
要避免的第二个问题是将您的请求包装在这样的任务中。它增加了代码的复杂性,使调试变得非常困难,而且没有必要。只需在方法级别添加async Task<>,然后让编译器为您处理连接:
async Task<User> GetDirectManagerForUser(GraphServiceClient _graphServiceClient, string managerId)
第三,您投射结果但没有捕获任何异常(即404您得到的)。您想要捕获这些并返回一个空用户:
var manager = await graphHelper.GetManagerForCurrentUser(userIdToCheck);
var allUsersConnectedToCurrentManagerDisplayName = manager.DisplayName;
var allUsersConnectedToCurrentManagerEmail = manager.UserPrincipalName;
var allUsersConnectedToCurrentManagerId = manager.Id;
async Task<User> GetDirectManagerForUser(GraphServiceClient _graphServiceClient, string managerId)
{
try
{
// Normal path
return await _graphServiceClient
.Users[managerId]
.Manager
.Request()
.GetAsync();
}
catch (Exception)
{
// Something went wrong or no manager exists
var emptyUser = new User();
}
}
TA贡献1804条经验 获得超2个赞
您必须捕获异常才能返回 null。我会这样写这个函数:
public User GetDirectManagerForUser(GraphServiceClient _graphServiceClient, string managerId)
{
//.Result, because this function in synchronious
try
{
var manager = await _graphServiceClient.Users[managerId].Manager.Request().GetAsync().Result;
return manager;
}
catch(Exception)
{
return null;
}
}
您还可以像这样使函数异步:
public async Task<User> GetDirectManagerForUser(GraphServiceClient _graphServiceClient, string managerId)
{
try
{
var manager = await _graphServiceClient.Users[managerId].Manager.Request().GetAsync();
return manager;
}
catch(Exception)
{
return null;
}
}
为什么没有指定可访问性级别?
- 2 回答
- 0 关注
- 81 浏览
添加回答
举报