This will give me like: http://api.com/main?id=1234,5678 but I want the style like above, e.g., http://api.com/main?id=1234&id=5678
I think the accept answer didn't address this issue from OP.
Using AddQueryString(string uri, IEnumerable<KeyValuePair<string, string>> queryString)
overload when you have an array you want to be part of the query string would only give you the comma-separated string as the parameter, and most of the time that is not what you want.
For example,
var endpoint = "v1/api/endpoint";
var arrayOfIds = new[] { "1", "2", "3" };
var queryString = new[]
{
new KeyValuePair<string,string>("id",new StringValues(arrayOfIds)),
new KeyValuePair<string,string>("other","value"),
...
};
var url = QueryHelpers.AddQueryString(endpoint, queryString);
The url at the end would look like (demo)
v1/api/endpoint?id=1,2,3&other=value
To get what OP wants, we will need to use the StringValues' overload AddQueryString(string uri, IEnumerable<KeyVaulePair<string, StringValues>> queryString)
.
For example,
var endpoint = "v1/api/endpoint";
var arrayOfIds = new[] { "1", "2", "3" };
var queryString = new []
{
new KeyValuePair<string, StringValues>("id", new StringValues(arrayOfIds)),
new KeyValuePair<string, StringValues>("other", "value")
};
var url = QueryHelpers.AddQueryString(endpoint, queryString);
Then the URL would look like (demo)
v1/api/endpoint?id=1&id=2&id=3&other=value
Bonus
Just in case you wonder why you don't see the StringValues' overload, even you are running on .NET 5+?
Maybe you have multiple versions of .NET installed, and your app is still referencing the old version 2.*, which is marked as deprecated recently.
To make sure you use the latest .NET, in your .csproj file, you can add the framework reference like the following:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
...
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
...
</Project>