4

Im making some automatic surveillance for an Rest API im running and i need to retrieve the response body from the HttpResponseMessage object. Im using Flurl Http: https://flurl.dev/docs/fluent-http/

I know how to retrieve the responsebody by adding ".RecieveSomeForm()" at the end of the http request, but i also need to get the response headers, as the error code from the Rest API is sent back as a header. My problem is that - to my knowledge and what i tried - its only the HttpResponseMessage object that i can retrieve the headers from. So the question is: How do i get the responsebody out of the HttpResponseMessage while still being able to retrieve the headers for error logging?

using (var cli = new FlurlClient(URL).EnableCookies())
{

//get response body - var is set to string and has only response body

var AsyncResponse = await cli.WithHeader("some header").Request("some end point").AllowAnyHttpStatus().PostJsonAsync(some body).ReceiveString();
Console.WriteLine(AsyncResponse);



//get headers - var is set to HttpResponseMessage

var AsyncResponse = await cli.WithHeader("some header").Request("some end point").AllowAnyHttpStatus().PostJsonAsync(some body);
Console.WriteLine(AsyncResponse.Headers);

}
Chris
  • 3,113
  • 5
  • 24
  • 46
RatzMouze
  • 351
  • 3
  • 13

1 Answers1

7

If I've understood correctly, you want Headers + Response body from a HTTP response.

var response = await cli.WithHeader("some header").Request("some end point").AllowAnyHttpStatus().PostJsonAsync("some body");

var headers = response.Headers; //do your stuff
var responseBody = response.Content != null ? await response.Content.ReadAsStringAsync() : null;

Another option which I personally don't like:

 var responseTask = cli.WithHeader("some header", "haha").Request("some end point").AllowAnyHttpStatus().PostJsonAsync("some body");

 var headers = (await responseTask).Headers; //do your stuff
 var responseBody = await responseTask.ReceiveString();

Unfortunately, Flurl's extension methods can be used on Task, not on HttpResponseMessage. (that's why you have to avoid awaiting in the first line of code)

  • 1
    This is probably the #1 complaint about Flurl and it is [_the_ top priority](https://github.com/tmenier/Flurl/issues/354) for 3.0. – Todd Menier Jun 22 '19 at 15:45