Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread was aborted issue in httpClient.PostAsync

While i am posting the request to the rest api the program will crash and Thread was being aborted will occured. please advice.

    public async Task<TResponse> Post<TRequest, TResponse>(string method, TRequest request)
    {
            JsonMediaTypeFormatter jsonFormat = new JsonMediaTypeFormatter
            {
                SerializerSettings =
                {
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                    PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None
                }
            };

            var response = await _httpClient.PostAsync(_baseUrl + method, request, jsonFormat);
            var finalResponse = await response.Content.ReadAsAsync<TResponse>();

            return finalResponse;
    }

please note that no request will be sent to the server. by the way the _httpClient will be defined as below

        _httpClient =
            new HttpClient(new HttpClientHandler
                {
                    AutomaticDecompression =
                        System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
                })
                {Timeout = TimeSpan.FromSeconds(50)};
        _httpClient.DefaultRequestHeaders.Add("Authorization", "apikey " + apiKey);
like image 551
Behzad Avatar asked Feb 06 '23 07:02

Behzad


2 Answers

I have figure it out by myself, turns out that PostAsync will call some other method which cancel the current thread. so i removed the await keyword and get the final result.

var response = _httpClient.PostAsync(_baseUrl + method, request, jsonFormat).Result;
like image 104
Behzad Avatar answered Feb 08 '23 16:02

Behzad


We also got the "Thread was being aborted" error.

For us, our call to httpClient.PostAsync was from a Unit Test.

Once we changed our Unit Test method signature to be async, and our invocation to await, the PostAsync succeeded.

[TestMethod]
public async Task Test_blah()
{
   ...
   // Act 
   var response = await testController.Call();
   ...
}
like image 38
Artie Leech Avatar answered Feb 08 '23 17:02

Artie Leech