Sujith
Sujith

Reputation: 11

HttpClient.SendAsync is throwing "A task was canceled" issue

We are making a PUT call to the service layer to update an entity information

HttpClient.SendAsync method is throwing "A task was canceled" issue even though the API call is successfully made to the backend service layer. I could see the logs from service layer.

Initially I thought it could be related to timeout, so I increased the timeout from 10 seconds to 30 seconds, still the program is waiting for 30 seconds and gets timed out with the error "A task was canceled". But the api call was successfully completed in Service Layer within even 5 seconds

Please find below my code

    protected override void Execute(CodeActivityContext context)
    {
        string uuid = UUID.Get(context);

        Console.WriteLine(uuid + ": Http Api Call - STARTED");

        string endPoint = EndPoint.Get(context);
        string contentType = ContentType.Get(context);
        string acceptFormat = AcceptFormat.Get(context);
        HttpMethod httpMethod = HttpApiMethod.Get(context);
        string clientCertificatePath = ClientCertificatePath.Get(context);
        string clientCertificatePassword = ClientCertificatePassword.Get(context);
        double httpTimeOut = HttpTimeout.Get(context);
        Dictionary<string, string> requestHeaders = RequestHeaders.Get(context);
        Dictionary<string, string> pathParams = PathParams.Get(context);
        Dictionary<string, string> queryParams = QueryParams.Get(context);
        string requestBody = RequestBody.Get(context);


        WebRequestHandler webRequestHandler = new WebRequestHandler();
        webRequestHandler.MaxConnectionsPerServer = 1;

        if (clientCertificatePath != null && clientCertificatePath.Trim().Length > 0)
        {
            X509Certificate2 x509Certificate2 = null;
            if (clientCertificatePassword != null && clientCertificatePassword.Trim().Length > 0)
            {
                x509Certificate2 = new X509Certificate2(clientCertificatePath.Trim(),
                    clientCertificatePassword.Trim());
            }
            else
            {
                x509Certificate2 = new X509Certificate2(clientCertificatePath.Trim());
            }
            webRequestHandler.ClientCertificates.Add(x509Certificate2);
        }

        HttpClient httpClient = new HttpClient(webRequestHandler)
        {
            Timeout = TimeSpan.FromMilliseconds(httpTimeOut)
        };

        if (acceptFormat != null)
        {
            httpClient.DefaultRequestHeaders.Add("Accept", acceptFormat);
        }

        HttpResponseMessage httpResponseMessage = InvokeApiSync(httpClient, endPoint,
                                     httpMethod, contentType,
                                     requestHeaders, pathParams,
                                     queryParams, requestBody,
                                     uuid
                                     );

        HttpResponseMessageObject.Set(context, httpResponseMessage);
        ResponseBody.Set(context, httpResponseMessage.Content.ReadAsStringAsync().Result);
        StatusCode.Set(context, (int)httpResponseMessage.StatusCode);

        Console.WriteLine(uuid + ": Http Api Call - ENDED");
    }

    private HttpResponseMessage InvokeApiSync(HttpClient httpClient,
                            string endPoint,
                            HttpMethod httpMethod,
                            string contentType,
                            Dictionary<string, string> requestHeaders,
                            Dictionary<string, string> pathParams,
                            Dictionary<string, string> queryParams,
                            string requestBody,
                            string uuid)
    {
        if (pathParams != null)
        {
            ICollection<string> keys = pathParams.Keys;
            if (keys.Count > 0)
            {
                foreach (string key in keys)
                {
                    endPoint = endPoint.Replace(":" + key, pathParams[key]);
                }
            }
        }

        if (queryParams != null)
        {
            List<string> keys = new List<string>(queryParams.Keys);
            if (keys.Count > 0)
            {
                endPoint = string.Concat(endPoint, "?", keys[0], "=", queryParams[keys[0]]);
                for (int index = 1; index < keys.Count; index++)
                {
                    endPoint = string.Concat(endPoint, "&", keys[index], "=", queryParams[keys[index]]);
                }
            }
        }

        try
        {
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(httpMethod, endPoint);
            if (requestHeaders != null)
            {
                foreach (string key in requestHeaders.Keys)
                {
                    httpRequestMessage.Headers.Add(key, requestHeaders[key]);
                }
            }

            if (httpMethod.Equals(HttpMethod.Put) || httpMethod.Equals(HttpMethod.Post))
            {
                StringContent reqContent = null;
                if (requestBody != null)
                {
                    reqContent = new StringContent(requestBody);
                }
                else
                {
                    reqContent = new StringContent("");
                }

                reqContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                httpRequestMessage.Content = reqContent;
            }

            HttpResponseMessage httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;

            return httpResponseMessage;
        }
        catch (Exception exception)
        {
            Console.WriteLine(uuid + " : HttpApi Error Has Occurred");
            Console.WriteLine(uuid + " : " + exception.Message);
            Console.WriteLine(uuid + " : " + exception.StackTrace);
            throw exception;
        }
    }

Any help would be much appreciated. Thanks.!

Upvotes: 0

Views: 475

Answers (0)

Related Questions