首页 > 解决方案 > 使用带有 HttpClient.GetAsync 方法的 LINQ(Skip and Take)方法来提高性能?

问题描述

我使用以下代码来检索 JSON 提要的内容,如您所见,我使用了如下分页技术SkipTake方法:

[HttpGet("[action]")]
public async Task<myPaginatedReturnedData> MyMethod(int page)
{
    int perPage = 10;
    int start = (page - 1) * perPage;

    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("externalAPI");
        MediaTypeWithQualityHeaderValue contentType =
            new MediaTypeWithQualityHeaderValue("application/json");
        client.DefaultRequestHeaders.Accept.Add(contentType);
        HttpResponseMessage response = await client.GetAsync(client.BaseAddress);
        string content = await response.Content.ReadAsStringAsync();
        IEnumerable<myReturnedData> data = 
               JsonConvert.DeserializeObject<IEnumerable<myReturnedData>>(content);
        myPaginatedReturnedData datasent = new myPaginatedReturnedData
        {
            Count = data.Count(),
            myReturnedData = data.Skip(start).Take(perPage).ToList(),
        };
        return datasent;
    }
}

我的分页工作正常,但是我看不到任何性能改进,我知道这是因为每次我请求一个新页面时,它都会一次又一次地调用 API,并在检索所有内容后,它使用SkipTake方法对其进行过滤,我正在寻找一种将SkipandTake方法与 my一起应用的方法,HttpClient以便它只检索每个页面所需的记录。可能吗?如果是这样,怎么做?

标签: c#angularlinqasync-await

解决方案


为了将 Take/Skip 应用于数据检索,服务器必须了解它们。您可以使用 IQueryable LINQ 提供程序来做到这一点(请参阅 [1] 以了解其复杂程度),或者更好的是,通过将适当的值传递给client.GetAsync调用,例如

HttpResponseMessage response = await client.GetAsync(client.BaseAddress + $"?skip={start}&take={perPage}");

当然,您的服务器端代码必须正确解释这些skiptake参数;这不是自动的

您可能还想查看 OData(请参阅 [2]),但我从未在生产中实际使用过它;我只知道它存在。

[1] https://msdn.microsoft.com/en-us/library/bb546158.aspx

[2] https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/calling-an-odata-service-from -a-net-client


推荐阅读