问题
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