获得响应标题

Rag*_*534 6 c# .net-core flurl

使用Flurl从API获取响应.

var response = await url.WithClient(fc)
            .WithHeader("Authorization", requestDto.ApiKey)
            .GetJsonAsync<T>();
dynamic httpResponse = response.Result;
Run Code Online (Sandbox Code Playgroud)

但我无法访问httpResponse.Headers

如何在使用GetJsonAsync时访问响应标头.

Ily*_*kov 8

您无法获取标头,GetJsonAsync<T>因为它返回Task<T>而不是原始响应.您可以GetAsync在下一步调用和反序列化您的有效负载:

HttpResponseMessage response = await url.GetAsync();

HttpResponseHeaders headers = response.Headers;

FooPayload payload = await response.ReadFromJsonAsync<FooPayload>();
Run Code Online (Sandbox Code Playgroud)

ReadFromJsonAsync 是一种扩展方法:

public static async Task<TBody> ReadFromJsonAsync<TBody>(this HttpResponseMessage response)
{
    if (response.Content == null) return default(TBody);

    string content = await response.Content.ReadAsStringAsync();

    return JsonConvert.DeserializeObject<TBody>(content);
}
Run Code Online (Sandbox Code Playgroud)

PS这就是为什么我更喜欢并建议使用原始HttpClient而不是任何第三方高级客户端,如RestSharp或Flurl.

  • @IlyaChumakov你所描述的Flurl的一个缺点("强迫你使用HttpResponseMessage进行低级操作")实际上是一个优势.Flurl的主要目标是适度:在最常见的95%场景中保存击键.而对于其他5%,可以轻松访问基础HttpClient API(正如您在此处所示),这样您就不会被卡住.(是的,我完全弥补了这些数字.:) (3认同)