. NET HttpClient медленно или не отвечает в Azure WebApp - PullRequest
1 голос
/ 22 февраля 2020

Мы запускаем WebJob и Api в Azure Службах приложений. Некоторые из WebJobs выполняют вызовы REST сторонним сервисам, таким как ebay. Все работало нормально, за несколько дней до go, когда службы начали выдавать эту ошибку случайным образом:

{\"ClassName\":\"System.Net.Http.HttpRequestException\",\"Message\":\"An error occurred while sending the request.\",\"Data\":{},\"InnerException\":{\"ClassName\":\"System.Net.WebException\",\"Message\":\"The underlying connection was closed: An unexpected error occurred on a receive.\",\"Data\":{},\"InnerException\":{\"ClassName\":\"System.IO.IOException\",\"Message\":\"Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.\",\"Data\":{},\"InnerException\":{\"NativeErrorCode\":10060,\"ClassName\":\"System.Net.Sockets.SocketException\",\"Message\":\"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond\",\"Data\":{},\"InnerException\":null,\"HelpURL\":null,\"StackTraceString\":\"   at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)\\r\\n   at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)\",\"RemoteStackTraceString\":null,\"RemoteStackIndex\":0,\"ExceptionMethod\":\"8\\nEndReceive\\nSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\\nSystem.Net.Sockets.Socket\\nInt32 EndReceive(System.IAsyncResult)\",\"HResult\":-2147467259,\"Source\":\"System\",\"WatsonBuckets\":null},\"HelpURL\":null,\"StackTraceString\":\"   at System.Net.Security._SslStream.EndRead(IAsyncResult asyncResult)\\r\\n   at System.Net.TlsStream.EndRead(IAsyncResult asyncResult)\\r\\n   at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)\",\"RemoteStackTraceString\":null,\"RemoteStackIndex\":0,\"ExceptionMethod\":\"8\\nEndRead\\nSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\\nSystem.Net.Security._SslStream\\nInt32 EndRead(System.IAsyncResult)\",\"HResult\":-2146232800,\"Source\":\"System\",\"WatsonBuckets\":null}

Вызовы иногда работают, но очень медленные и иногда возвращают ошибку. Запуск локального экземпляра службы не приводит к сбою. Эти проблемы возникают только в производственной среде.

Мы используем одноэлементный экземпляр HttpClient для выполнения вызовов.

public sealed class Client : HttpClient
    {
        private static volatile Client _instance = new Client();

        static Client()
        {
        }

        private Client() : base(new NativeMessageHandler())
        {
            // limit the connections in parallel to 100 by default
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            // if this setting does not work, follow these instructions on app.config
            // ServicePointManager.DefaultConnectionLimit needs to be set before the ServicePoint is created 
            ServicePointManager.DefaultConnectionLimit = 100;
        }

        public static Client Instance => _instance;
    }

Мы вызываем конечную точку с помощью клиента следующим образом:

var client = Client.Instance;
var authenticationHeader = new AuthenticationHeaderValue("Bearer", token.AuthToken);
var url = "https://api.ebay.com/sell/account/v1/fulfillment_policy?marketplace_id=EBAY_DE";
var response = await client.GetMessageAsync(url, m => m.Headers.Authorization = authenticationHeader);

Метод GetMessageAsyn c является методом расширения и просто выполняет действие для установки заголовка.

Проблемы начались вскоре после того, как Microsoft анонсировала это обновление для системы безопасности: https://docs.microsoft.com/answers/questions/6842/announcement-samesite-cookie-handling-and-net-fram.html

Клиент настроен на прием TLS 1.2 и 1.1.

1 Ответ

1 голос
/ 26 февраля 2020

Чтобы сузить возможные причины, я попросил ebay и службу поддержки Microsoft проверить их системы. Оказалось, на самом деле проблема на стороне Ebay.

...