Microsoft.Exchange.WebServices:无法将数据写入传输连接:远程主机强行关闭了现有连接

Microsoft.Exchange.WebServices : Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host

我正在尝试使用 Microsoft.Exchange.WebServices.dll (EWS Apis)

在 Office 365 上保存电子邮件
     EmailMessage f_ObjEWSMail  = new EmailMessage(objExchangeService);
     f_ObjEWSMail.Save(p_objFoderID); // Throwing error here

它随机抛出异常:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

at System.Net.Security._SslStream.EndRead(IAsyncResult asyncResult)

at System.Net.TlsStream.EndRead(IAsyncResult asyncResult)

at System.Net.PooledStream.EndRead(IAsyncResult asyncResult)

at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)

或者有时会抛出:

The request failed. The underlying connection was closed: An unexpected error occurred on a receive.

Stack Strace :: at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request) at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request) at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest1.Execute() at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalCreateItems(IEnumerable1 items, FolderId parentFolderId, Nullable1 messageDisposition, Nullable1 sendInvitationsMode, ServiceErrorHandling errorHandling) at Microsoft.Exchange.WebServices.Data.Item.InternalCreate(FolderId parentFolderId, Nullable1 messageDisposition, Nullable1 sendInvitationsMode) at Microsoft.Exchange.WebServices.Data.Item.Save(FolderId parentFolderId) at Office365EWSWriter.Office365Engine.SaveMail(EmailMessage p_objEWSMailItem, FolderId p_objFoderID)

请提出解决方案。

这些错误是由于底层传输连接问题(例如您与云的网络连接)造成的,因为您与云打交道时无法保证 100% 的网络(例如与 Onprem 相比,您只是连接到服务器通过交换机)。在这种情况下,您所能做的就是捕获错误并重试。 EWS Managed API 正在使用 HttpWebRequest 发送和接收 SOAP 数据包,因此这些错误是由客户端的 class 生成的(如果您想进一步追踪这些错误,那么我建议在 Whosebug 中搜索这些错误class 上的错误)。如果您尝试使用基于云的虚拟机(或服务)(如 AWS 或 Azure)中的代码,您应该会发现这些错误的实例要少得多,因为底层网络连接更加可靠。