通过Swagger调用Microsoft Graph API时无限挂起的问题排查
问题解决:Swagger调用Microsoft Graph API时无限挂起
问题根源
你遇到的是典型的异步线程死锁问题:在ASP.NET环境下(Swagger调用会触发该环境),用.GetAwaiter().GetResult()同步阻塞异步方法时,ASP.NET的SynchronizationContext会持有当前线程,而异步操作完成后需要回到这个上下文继续执行,导致双方互相等待,最终无限挂起。其他测试方式(比如控制台程序)没有这个上下文限制,所以不会触发死锁。
解决方案
方案1:将控制器方法改为异步(推荐,符合.NET异步规范)
把控制器的void方法改成async Task,用await调用Graph API的异步方法,避免阻塞线程:
[HttpGet] [Route("api/CoreUserController/RunUserSyncTest")] public async Task RunUserSyncTest() { string tenantId = "My Tenant Id"; string clientId = "My Client Id"; string clientSecret = "My Client Secret"; string[] scopes = new[] { "https://graph.microsoft.com/.default" }; Azure.Identity.TokenCredentialOptions options = new Azure.Identity.TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud }; Azure.Identity.ClientSecretCredential clientSecretCredential = new Azure.Identity.ClientSecretCredential(tenantId, clientId, clientSecret, options); Microsoft.Graph.GraphServiceClient graphServiceClient = new Microsoft.Graph.GraphServiceClient(clientSecretCredential, scopes); var usersResponse = await graphServiceClient.Users.GetAsync(requestConfiguration => { requestConfiguration.QueryParameters.Filter = "accountEnabled eq true"; }); }
方案2:临时规避(不推荐,仅作应急)
如果暂时无法修改方法签名,可以在调用异步方法时添加.ConfigureAwait(false),让异步操作完成后不回到原上下文,避免死锁:
var usersResponse = graphServiceClient.Users.GetAsync(requestConfiguration => { requestConfiguration.QueryParameters.Filter = "accountEnabled eq true"; }).ConfigureAwait(false).GetAwaiter().GetResult();
注意:这个方法只是临时 workaround,长期来看还是推荐使用方案1——同步阻塞异步方法会破坏.NET异步编程模型,可能引发其他潜在问题。
额外说明
- Swagger调用时运行在ASP.NET请求上下文里,该上下文会限制线程调度;而控制台或单元测试通常没有这个上下文,所以不会出现死锁。
- 永远不要在ASP.NET请求上下文中用
.Wait()、.Result()或.GetAwaiter().GetResult()阻塞异步方法,这是引发死锁的常见原因。
内容的提问来源于stack exchange,提问作者amg
相关产品推荐
相关产品推荐

