I wrote this extension method for HttpClient
to be synchronous and used in Blazor WebAssembly:
public static class HttpClientExtensions
{
public static TR PostAsJsonAsync2<T, TR>(this HttpClient client, string path, T model) where T : class
{
TR result = default(TR);
client.PostAsJsonAsync<T>(path, model).ContinueWith(async (httpResponse) =>
{
Console.WriteLine($"Ran Successfuly");
if ((await httpResponse).IsSuccessStatusCode)
{
Console.WriteLine("Response Success.");
// Following is OK and returns the result (true)
result = await (await httpResponse).Content.ReadFromJsonAsync<TR>();
Console.WriteLine($"Result: {result}");
return result;
}
else
{
throw new Exception("Error from app. not success status code.");
}
});
// the result is false
Console.WriteLine($"Result to return: {result}");
return result;
}
}
About to Request.
Result to return: False
Ran Successfuly
Response Success.
True
how to wait for PostAsJsonAsync()
and ContinueWith()
without using Wait()
or Result()
or any way to correctly return the result. and maintain the function synchronous.