5

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);

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

Comments

4

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();
   ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.