Use LINQ (Skip and Take) methods with HttpClient.GetAsync method for improving performance?

可紊 提交于 2020-01-14 03:14:09

问题


I have used the following code to retrieve the content of a JSON feed and as you see I have used the paging techniques and Skip and Take methods like this:

[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;
    }
}

My paging works fine, however I can't see any performance improvement and I know this is because every time I request a new page it calls the API again and again and after retrieving all contents, it filters it using Skip and Take methods, I am looking for a way to apply the Skip and Take methods with my HttpClient so that it only retrieves the needed records for every page. Is it possible? If so, how?


回答1:


In order to apply the Take/Skip to the data retrieval, the server would have to know about them. You could do that with an IQueryable LINQ provider (see [1] for getting only an idea of how complex that is) or, better, by passing the appropriate values to the client.GetAsync call, something like

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

Of course, your server-side code has to interpret those skip and take parameters correctly; it's not automatic.

You might also want to look at OData (see [2]), but I have never actually used it in production; I just know it exists.

[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



来源:https://stackoverflow.com/questions/50076579/use-linq-skip-and-take-methods-with-httpclient-getasync-method-for-improving-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!