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);
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;
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();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With