【问题标题】:.net core 2.2 httpclient Factory not giving Full data as response.net core 2.2 httpclient 工厂未提供完整数据作为响应
【发布时间】:2020-03-05 18:40:21
【问题描述】:

我在我的航班列表应用程序中使用 .net core 2.2,为此我使用 wego api。但是当我使用下面的代码从 wego api 获取航班时,我没有得到完整的响应,但在邮递员中,我在一个请求中得到了完整的结果集。

public async Task<SearchResultMv> GetFlights(FlightParam flightParam, AuthResult auth)
{
    var request = new HttpRequestMessage(HttpMethod.Get, "https://srv.wego.com/metasearch/flights/searches/" + flightParam.SearchId + "/results?offset=0&locale=" + flightParam.locale + "&currencyCode=" + flightParam.currencyCode);
    request.Headers.Add("Bearer", auth.access_token);
    request.Headers.Add("Accept", "application/json");

    var client = _httpClient.CreateClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.access_token);

    var response = await client.SendAsync(request).ConfigureAwait(false);

    SearchResultMv json = new SearchResultMv();

    response.EnsureSuccessStatusCode();

    if (response.IsSuccessStatusCode)
    {
        json = await response.Content.ReadAsAsync<SearchResultMv>().ConfigureAwait(false);
        return json;
    }
}

有时我没有得到上述代码设置的任何结果。 Wego api 没有在这个 api 上提供任何分页或过滤。所以请帮助我实现这一目标。感谢提前。

【问题讨论】:

  • 您应该发送邮递员的图像和 wego api 文档的图像或链接。

标签: asp.net-core .net-core asp.net-core-webapi asp.net-core-2.2 httpclientfactory


【解决方案1】:

根据他们的文档,您需要轮询他们的 API 以逐步获得结果。您还需要在返回结果时增加偏移量。

例如,如果第一组结果为您提供 100 个结果,则以下请求应将偏移值设置为 100。offset=100

文档: https://developers.wego.com/affiliates/guides/flights

编辑 - 添加示例解决方案

每秒轮询 API 直到达到所需结果数量的示例代码。此代码尚未经过测试,因此您需要根据需要对其进行调整。

const int numberOfResultsToGet = 100;
var results = new List<SearchResultMv>();

while (results.Count < numberOfResultsToGet)
{
    var response = await GetFlights(flightParam, auth);
    results.AddRange(response.Results);

    // update offset
    flightParam.Offset += response.Results.Count;

    // sleep for 1 second before sending another request
    Thread.Sleep(TimeSpan.FromSeconds(1));
}

更改您的请求以使用动态 Offset 值。您可以将Offset 属性添加到FlightParam 类中。

var request = new HttpRequestMessage(
    HttpMethod.Get, 
    $"https://srv.wego.com/metasearch/flights/searches/{flightParam.SearchId}/results?" +
    $"offset={flightParam.Offset}" +
    $"&locale={flightParam.locale}" +
    $"&currencyCode={flightParam.currencyCode}");

【讨论】:

  • 是的,但大多数时候第一次请求我没有得到任何结果。 :(
  • 不保证您在第一次请求中会有任何结果。这取决于启动搜索后生成搜索结果需要多长时间。这就是为什么你需要处理你身边的逻辑。您可以编写一些代码以每秒发送一个请求,直到获得所需的结果数。
  • 那么我该如何进行他们在文档中提到的客户端过滤。
  • 我在答案中添加了一个示例,以便您有一个想法。
  • 非常感谢,让我检查一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 2019-01-11
  • 1970-01-01
  • 2019-12-26
  • 2014-03-03
相关资源
最近更新 更多