0

When using a http client in an azure function (.Net 6), the body is null when received.

Here is what is called:

await _httpClient.PostAsJsonAsync(uri, value);

If I do the same thing in a web api (same code in .Net 6), it works. Following the reference in PostAsJsonAsync, the function points to HttpClientExtensions in System.Net.Http, and the web api references HttpClientJsonExtensions in System.Net.Http.Json.

If I add the following to the function:

<PackageReference Include="System.Net.Http.Json" Version="6.0.0" />

It still uses HttpClientExtensions in System.Net.Http.

The only way I could get it to work in a function is by explicitly calling the static class:

await HttpClientJsonExtensions.PostAsJsonAsync(_httpClient, uri, value);

Would this be the only way to use this for a function? Why does the web api HttpClient use the System.Net.Http.Json, but the function needs to pass in the HttpClient as a parameter to PostAsJsonAsync.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75

1 Answers1

0

It still uses HttpClientExtensions in System.Net.Http.

  • In place of System.Net.Http, you have to use the reference of System.Net.Http.Formatting.dll for using the HttpClient

but the function needs to pass in the HttpClient as a parameter to PostAsJsonAsync.

  • There are few methods given in this MS Doc regarding how HttpClient is passed as a parameter to the PostAsJsonAsync but you can use PostAsync call with the above new dll referencing.

  • As one of the similar issues registered on the GitHub Repo of Azure Functions Dotnet - body is null when using HttpClient in the PostAsJsonSync Method/call, thanks to @waynedavisactivu's workaround:

var content = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
var response = await client.PostAsync("api/wh/link", content);

///Azure Function HttpRequestData.Body contains data
Pravallika KV
  • 2,415
  • 2
  • 2
  • 7