本文介绍了将LINQ(跳过和获取)方法与HttpClient.GetAsync方法一起使用以提高性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用以下代码来检索JSON feed的内容,并且如您所见,我已经使用了分页技术以及SkipTake这样的方法:

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

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

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?

推荐答案

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

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}");

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

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

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

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/zh-我们/library/bb546158.aspx

[2] https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/odata-support-in- aspnet-web-api/odata-v3/从一个网络客户端调用一个odata-service-

这篇关于将LINQ(跳过和获取)方法与HttpClient.GetAsync方法一起使用以提高性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 19:50