简体   繁体   中英

The web server hangs while calling 3rd party Web API from my Web API

I need to call a 3 party Web Api from my ASP.net Web API, when it runs the line

HttpResponseMessage response = await client.PostAsJsonAsync("api/ArTrx/postDocument", poMaster);

the web server hangs. I have tried to put below code in to a console program, it runs well. What is wrong with below code when run in ASP.net Web API project?

client.BaseAddress = new Uri(webAPIAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

string token = Crypto.EncryptStringAES("abcd1234");
client.DefaultRequestHeaders.Add("X-Token", token);

HttpResponseMessage response = await client.PostAsJsonAsync("api/ArTrx/postDocument", poMaster);    
if (response.IsSuccessStatusCode)
{
    ...
}

You probably have a Task<T>.Result or Task.Wait call further up your call stack. This will cause a deadlock on ASP.NET that I describe in more detail on my blog.

In summary, await will capture a "context" - in this case, an ASP.NET request context, which only allows one running thread at a time. When its awaitable completes (that is, when the POST finishes), the async method will continue in that context . If your code is blocking further up the call stack (eg, Result or Wait ), then it will block a thread in that ASP.NET request context, and the async method cannot enter that context to continue executing.

You don't see the deadlock in the Console app because there's no context being captured, so the async method resumes on a thread pool thread instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM