从 Flurl HttpResponseMessage 获取响应正文

Rat*_*uze 3 c# flurl

我正在对正在运行的 Rest API 进行一些自动监视,我需要从 HttpResponseMessage 对象中检索响应正文。我使用 Flurl http:https ://fluurl.dev/docs/fluent-http/

我知道如何通过在 http 请求的末尾添加“.RecieveSomeForm()”来检索响应主体,但我还需要获取响应标头,因为来自 Rest API 的错误代码作为标头发回。我的问题是 - 据我所知和我尝试过的 - 它只是我可以从中检索标题的 HttpResponseMessage 对象。所以问题是:如何在仍然能够检索标题以进行错误记录的同时从 HttpResponseMessage 中获取响应体?

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);

}
Run Code Online (Sandbox Code Playgroud)

Ciu*_*rin 6

如果我理解正确,您需要来自 HTTP 响应的 Headers + Response body。

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;
Run Code Online (Sandbox Code Playgroud)

我个人不喜欢的另一种选择:

 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();
Run Code Online (Sandbox Code Playgroud)

不幸的是,Flurl 的扩展方法可以用于Task,而不是用于HttpResponseMessage。(这就是为什么你必须避免在第一行代码中等待)