Consider this non-async method called Forward
which works exactly as expected when called (in C#) with Forward(forwardUrl, content);
private ActionResult Forward(string forwardUrl, FormUrlEncodedContent content)
{
// NOTE - httpClient is a static HttpClient instance
HttpResponseMessage response;
switch (Request.RequestType.ToUpperInvariant())
{
case "GET":
response = httpClient.GetAsync(forwardUrl).GetAwaiter().GetResult();
break;
case "POST":
response = httpClient.PostAsync(forwardUrl, content).GetAwaiter().GetResult();
break;
default:
throw new InvalidOperationException($"Unable to forward Request method {Request.RequestType}.");
}
if (response.IsSuccessStatusCode)
{
return Content(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), response.Content.Headers.ContentType.ToString());
}
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
That one works fine, but repeatedly calls GetAwaiter().GetResult()
which essentially blocks and makes it syncronous.
Now I have the following async method called ForwardAsync
and here I call it with exactly the same arguments, but with the calling pattern of ForwardAsync(forwardUrl, content).GetAwaiter().GetResult();
private async Task<ActionResult> ForwardAsync(string forwardUrl, FormUrlEncodedContent content)
{
HttpResponseMessage response;
switch (Request.RequestType.ToUpperInvariant())
{
case "GET":
response = await httpClient.GetAsync(forwardUrl);
break;
case "POST":
response = await httpClient.PostAsync(forwardUrl, content);
break;
default:
throw new InvalidOperationException($"Unable to forward Request method {Request.RequestType}.");
}
if (response.IsSuccessStatusCode)
{
return Content(await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentType.ToString());
}
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
This one simply hangs. In my test case I am going down the POST
branch (in both scenarios) but the code never returns from await httpClient.PostAsync(forwardUrl, content)
. I am able to confirm that the request is posted, and the code does run on the forwarded URL, and responds, but the awaited method invocation simply doesn't return.
What am I doing wrong?