Call external api from Web API synchronously
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.
mayabelle
I am a full-time mid-level web and application developer working in all application layers, with experience primarily in C#/.NET, MVC, MS SQL/T-SQL, JavaScript/JQuery/AJAX, CSS, HTML5, LINQ, HTTP, Visual Studio, TFS, and more.
Updated on April 23, 2020Comments
-
mayabelle about 4 years
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?