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()
:
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.
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