使用OAuth2.0连接Outlook时抛出“基础连接已关闭”错误求助
排查OAuth2.0连接Outlook时的连接关闭异常
我参考微软官方示例编写了一段C#代码,通过OAuth2.0连接Outlook,但运行时抛出异常:The underlying connection was closed: An unexpected error occurred on a send.
代码片段如下:
// Using Microsoft.Identity.Client 4.22.0 var cca = ConfidentialClientApplicationBuilder .Create(System.Configuration.ConfigurationManager.AppSettings["appId"]) .WithClientSecret(System.Configuration.ConfigurationManager.AppSettings["clientSecret"]) .WithTenantId(System.Configuration.ConfigurationManager.AppSettings["tenantId"]) .Build(); var ewsScopes = new string[] { "https://outlook.office365.com/.default" }; try { var authResult = await cca.AcquireTokenForClient(ewsScopes) .ExecuteAsync(); // Configure the ExchangeService with the access token var ewsClient = new ExchangeService(); ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken); ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "capmodauthtesting@test.com"); //Include x-anchormailbox header ewsClient.HttpHeaders.Add("X-AnchorMailbox", "capmodauthtesting@test.com"); // Make an EWS call var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10)); foreach(var folder in folders) { Console.WriteLine("Folder: {folder.DisplayName}"); } } catch (MsalException ex) { Console.WriteLine("Error acquiring access token: {ex}"); } catch (Exception ex) { //Console.WriteLine("Error: {ex}"); MessageBox.Show(ex.InnerException.Message); } if (System.Diagnostics.Debugger.IsAttached) { Console.WriteLine("Hit any key to exit..."); Console.ReadKey(); }
该代码来源于微软官方文档,请求协助排查该异常原因。
内容的提问来源于stack exchange,提问作者niran kumar
相关产品推荐
相关产品推荐

