微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用ASP.NET Core MVC中设置的AddHttpClient翻页API结果?

如何解决如何使用ASP.NET Core MVC中设置的AddHttpClient翻页API结果?

我跟随tutorial讨论了如何设置和使用HttpClient为ASP.NET Core 3.1 MVC应用程序进行API调用。我的设置使用ConnectWise Manage API,每个调用最多可以检索1000条记录。

我想检索一个项目的所有记录,但是我不知道如何在我的方法中实现分页。该API有两种分页类型:可导航和仅向前。导航链接包括响应链接头中的nextprevfirstlast链接。如果有更多记录,我将使用仅向前转发,它仅包含next链接(如果没有,则为空)。从技术上讲,所有结果都在第1页,因此API使用参数pageId确定要检索的下一条记录。链接标头中响应的next链接将包含下一个pageId

下面,我在Startup.cs中使用命名客户端"connectWiseManage"进行配置,并使用GetProductsById API调用方法获取记录。这段代码有效,虽然我找到了way to get the next link,但目前我只能获得第一页,而且我不知道如何分页获取所有记录。

我猜想在通过API分页获取所有记录时,请求应该在while循环内,并且只要Link头中有内容,就可以进行迭代。我还考虑过仅从链接提取pageId并将其替换为硬编码的链接,但是我无法弄清楚两者的逻辑。

如何通过设置检索所有记录?

public class ConnectWiseManageApi : IConnectWiseManageRepo
{
    private readonly IHttpClientFactory _clientFactory;

    public ConnectWiseManageApi(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task<List<ProductCwData>> GetProductsById(int productId)
    {
        HttpClient client = _clientFactory.CreateClient("connectWiseManage");

        List<ProductCwData> products = new List<ProductCwData>();
        int pageId = 1; //starting pageId must be 1

        try
        {                    
            HttpResponseMessage response = await client.GetAsync($"procurement/catalog?conditions=" +
               $"category/id={productId}" +
               $"&pagesize=10&pageid={pageId}");
            products = await response.Content.ReadFromJsonAsync<List<ProductCwData>>();
            IEnumerable<string> linkHeaderValues = new List<string>();
            response.Headers.TryGetValues("Link",out linkHeaderValues);
            //here,I Could extract the 'next' link from linkHeaderValues: https://stackoverflow.com/a/46328155/12300287
        }
        catch (Exception ex)
        {
            string errorMessage = ex.Message;
            throw;
        }

        return products;
    }
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    IAppSettings appSettings = new AppSettings();
    Configuration.Bind("AppSettings",appSettings);

    services.AddHttpClient();
    services.AddHttpClient("connectWiseManage",client =>
    {
        //All of the header values should be in appsettings.
        client.BaseAddress = new Uri("connectWiseManage");
        client.DefaultRequestHeaders.Add("clientId",appSettings.ConnectWiseManageAPI.ClientID);
        client.DefaultRequestHeaders.Add("Accept",appSettings.ConnectWiseManageAPI.Accept);
        client.DefaultRequestHeaders.Add("version",appSettings.ConnectWiseManageAPI.Version);
        client.DefaultRequestHeaders.Add("pagination-type","forward-only");
        string companyId = appSettings.ConnectWiseManageAPI.CompanyID;
        string publicKey = appSettings.ConnectWiseManageAPI.PublicKey;
        string privateKey = appSettings.ConnectWiseManageAPI.PrivateKey;
        //https://stackoverflow.com/a/14628308/12300287
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue(
                "Basic",Convert.ToBase64String(
                    System.Text.ASCIIEncoding.ASCII.GetBytes(
                       $"{companyId}+{publicKey}:{privateKey}"))); //encodes "companyID+publicKey:privateKey" in base64 as required for CW api
    });

    //dependency injection
    services.AddSingleton(appSettings);
    services.AddScoped<IConnectWiseManageRepo,ConnectWiseManageApi>();

    // ...

    services.AddControllersWithViews();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。