首页 > 解决方案 > Azure 函数 httpclient ObjectDisposedException 无法访问已处置的对象 SslStream

问题描述

当我从 Azure 函数发出 Post 请求时,我得到了这个 ObjectDisposedException。我在真正的天蓝色函数环境和函数本地调试中都看到了这个问题。我相信这是由于目标服务的大量响应体而发生的。但不确定。

以下是代码和详细的错误消息。我在“等待 httpClient.SendAsync(requestMessage).ConfigureAwait(false)”行中收到此错误

此代码运行良好,并在不在 Azure func 环境中的本地脚本中尝试时得到 200 响应。

 try
            {
                using (HttpResponseMessage response = await httpClient.SendAsync(requestMessage).ConfigureAwait(false))
                {
                    var responseHeaders = string.Join(" | ", response.Headers.Select(h => $"{h.Key} : {h.Value}"));
                    sbHeaders.Append($" :: Response- {responseHeaders}");

                    string content = await response.Content.ReadAsStringAsync();
                    try
                    {
                        response.EnsureSuccessStatusCode();
                    }
                    catch (HttpRequestException ex)
                    {
                        // This try catch is to handle any unsuccessful service response (service has handled the request)
                        string errorMessage = $"{requestMessage.RequestUri.ToString()} failed!. Headers: {sbHeaders.ToString()} :: Server response: {content}";
                        throw new CustomException(serviceAlias, response.StatusCode, errorMessage, ex);
                    }

                    var responseEntity = JsonConvert.DeserializeObject<TResponse>(content);
                    return responseEntity;
                }
            }
            catch (Exception ex)
            {
                // This try catch is to handle any network error (service HAS NOT handled the request)
                string errorMessage = $"{requestMessage.RequestUri.ToString()} failed!. Headers: {sbHeaders.ToString()} :: Server response: [{ex.GetType().Name}]{ex.Message}";
                throw new CustomException(serviceAlias, HttpStatusCode.InternalServerError, errorMessage, ex);
            }



System.IO.IOException: The read operation failed, see inner exception. ---> 
System.ObjectDisposedException: Cannot access a disposed object.\r\nObject name: 'SslStream'.\r\n   at System.Net.Security.SslState.ThrowIfExceptional()\r\n
   at System.Net.Security.SslState.CheckThrow(Boolean authSuccessCheck, Boolean shutdownCheck)\r\n  
   at System.Net.Security.SslState.CheckOldKeyDecryptedData(Memory`1 buffer)\r\n 
   at System.Net.Security.SslState.HandleQueuedCallback(Object& queuedStateRequest)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n  
   at System.Net.Security.SslStreamInternal.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)\r\n   --- End of inner exception stack trace ---\r\n  
   at System.Net.Security.SslStreamInternal.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)\r\n  
   at System.Net.Http.HttpConnection.FillAsync()\r\n   at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)\r\n   
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)\r\n   --- End of inner exception stack trace ---\r\n 
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)\r\n   
   at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)\r\n 
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)\r\n  
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n 
   at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n  
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)\r\n  
   at Microsoft.Ingestion.Stitch.Function.StitchServiceClient.SendRequestMessageInternalAsync[TResponse](HttpRequestMessage requestMessage, MicroServiceAlias serviceAlias) in E:\\Agent_work\\21\\s\\Src\\Stitch.Function\\Clients\\StitchServiceClient.cs:line 229"```

标签: c#.net-coreazure-functionsdotnet-httpclient

解决方案


请检查using 语句的工作原理。

在您的代码客户端中disposed,一旦using块结束,您仍然有待处理的任务content将尝试访问它。您需要在客户端中使用 block 获得结果


推荐阅读