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?
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()
:It's the same whether it's a
Task
orTask<T>
, it's the same callawait
translates to (although withawait
the task already completed) andTask.Result
(orTask.Wait
) wraps any exceptions inAggregateException
whileGetAwaiter().GetResult()
throws only the firstException
asawait
does.