Call external api from Web API synchronously

2020-05-24 23:02发布

I need to call an external api from my Web API 2 controller, similar to the requirement here:

Calling external HTTP service using HttpClient from a Web API Action

However, the solution above requires adding the async keyword to my api method's GET call, thus making my call asynchronous. I prefer to present clients of my API with a synchronous method but still be able to call the external api from my own (and will need that to return before my api returns). Is there a way to do this?

1条回答
迷人小祖宗
2楼-- · 2020-05-24 23:24

Blocking on an async operation could be dangerous. It hurts performance and could lead to deadlocks (more in Should I expose synchronous wrappers for asynchronous methods?)

But if you're sure that's what you want to do, It's better IMO to use GetAwaiter().GetResult():

using (HttpClient httpClient = new HttpClient())
{
    var response = httpClient.GetAsync(_endpoint).GetAwaiter().GetResult();
    var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    // Do stuff...
}

It's the same whether it's a Task or Task<T>, it's the same call await translates to (although with await the task already completed) and Task.Result (or Task.Wait) wraps any exceptions in AggregateException while GetAwaiter().GetResult() throws only the first Exception as await does.

查看更多
登录 后发表回答