How to utilize multiple parameters in a httpclient request in ASP.NET Core 7

335 views Asked by At

I am trying to pull multiple products from a shopify API as seen in their curl request in the documentation here:

curl -X GET "https://your-development-store.myshopify.com/admin/api/2023-
10/products.json?ids=632910392%2C921728736" \
-H "X-Shopify-Access-Token: {access_token}"

I however am using .NET Core 7 and need to use HttpClient and utilize the following code:

[HttpPost(Name = "PostDataExport")]
[EnableRateLimiting("api")]
public async Task<IActionResult> Post([FromBody] CustomerInquiry customerInquiry)
{
    try
    {
        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get,
                                     "https://mysite.myshopify.com/admin/api/2023-10/products.json?ids=7741485383833%7745763508377%7745765671065%7744839811225%7746517794969")
        {
            Headers =
            {
                { "X-Shopify-Access-Token", _shopifyAPIAuth.AccessToken }
            }
        };

        var httpClient = _httpClientFactory.CreateClient();
        var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);

        if (httpResponseMessage.IsSuccessStatusCode)
        {
            var content = await httpResponseMessage.Content.ReadAsStringAsync();
            return Ok(shopifyResponse);
        }

        return Ok("failed");
    }
    catch (Exception ex)
    {
        _logger.LogInformation("Message: Error: " + ex.ToString(), DateTime.UtcNow.ToLongTimeString());
        throw;
    }
}

The issue is this only seems to return the first product id in the list. If I switch the order then it the new first id in the list is pulled.

Am I using this incorrectly? Also, is there a cleaner way to write out parameters like this rather than putting in the url directly?

1

There are 1 answers

0
akseli On

You seem to be running into an encoding issue with your URL.

As a workaround, instead of:

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get,
 "https://mysite.myshopify.com/admin/api/2023-10/products.json?ids=7741485383833%7745763508377%7745765671065%7744839811225%7746517794969")

Try using an absolute URI:

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get,
 new Uri("https://mysite.myshopify.com/admin/api/2023-10/products.json?ids=7741485383833%7745763508377%7745765671065%7744839811225%7746517794969").AbsoluteUri);

A similar issue was reported here.