c# - 使用带有 HttpClient.GetAsync 方法的 LINQ(Skip and Take)方法来提高性能?
问题描述
我使用以下代码来检索 JSON 提要的内容,如您所见,我使用了如下分页技术Skip
和Take
方法:
[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,并在检索所有内容后,它使用Skip
和Take
方法对其进行过滤,我正在寻找一种将Skip
andTake
方法与 my一起应用的方法,HttpClient
以便它只检索每个页面所需的记录。可能吗?如果是这样,怎么做?
解决方案
为了将 Take/Skip 应用于数据检索,服务器必须了解它们。您可以使用 IQueryable LINQ 提供程序来做到这一点(请参阅 [1] 以了解其复杂程度),或者更好的是,通过将适当的值传递给client.GetAsync
调用,例如
HttpResponseMessage response = await client.GetAsync(client.BaseAddress + $"?skip={start}&take={perPage}");
当然,您的服务器端代码必须正确解释这些skip
和take
参数;这不是自动的。
您可能还想查看 OData(请参阅 [2]),但我从未在生产中实际使用过它;我只知道它存在。
推荐阅读
- json - JSON - Unity:如何序列化列表?NullReferenceException 错误
- android - 如何在 ViewModel 中访问 SharedPreferences?
- angular - 如何从应用模块中导入的模块访问组件?
- python - TensorBoard 未启动任何图表
- c# - 从 Windows 服务启动进程
- c# - 从 CSV 文件解析字符串,与字符串数组进行比较以打印特定行
- java - Eclipse 插件的自动安装依赖项
- sql - 如何替换动态光标以获得更好的性能?
- php - 在 yii2 activeform 中上传图片
- azure - 将证书导入 Azure Key Vault:密钥在指定状态下无效