Can I add a list or array of query strings to uribuilder?

1.2k Views Asked by At

I'm using UriBuilder to create a url for an API endpoint.

I need to add some query strings for it, and I can do that nicely with the following example:

    private async Task<string> CallAPI(string url, string queryString)
    {
        string s = "https://mysite.wendesk.com/api/v2/search/export/";
        UriBuilder uriBuild = new UriBuilder(s);
        uriBuild.Query = queryString;
        using (var result = await _HttpClient.GetAsync($"{uriBuild.Uri.ToString()}"))
        {

            if (!result.IsSuccessStatusCode)
            {
                throw new Exception("bad status code from zendesk");
            }
            return await result.Content.ReadAsStringAsync();
        }

    }

Which is easy and nice. But I need to a quite a few query strings, and depending on who's calling the function, I need varying amounts. So another solution could be something like this:

    private async Task<string> CallAPI(string url, string[] queryStrings)
    {
        string s = "https://mysite.wendesk.com/api/v2/search/export/";
        UriBuilder uriBuild = new UriBuilder(s);
        uriBuild.Query = string.Join("&", queryStrings);
        using (var result = await _HttpClient.GetAsync($"{uriBuild.Uri.ToString()}"))
        {

            if (!result.IsSuccessStatusCode)
            {
                throw new Exception("bad status code from zendesk");
            }
            return await result.Content.ReadAsStringAsync();
        }

    }

But I was wondering if there was something that could feel more "native". Perhaps something like creating a dicitionary with keys and values, so that the caller could just create a dictionary instead of hardcoding so much of the query strings in there?

1

There are 1 best solutions below

2
Bzafer On

I think NameValueCollection might work for a solution like you mentioned. You can use a dynamically method.

For example:

     private Task<string> CreateQuery(NameValueCollection nvc)
{
    var values = from key in nvc.AllKeys
        from value in nvc.GetValues(key)
        select string.Format(
            "{0}={1}",
            HttpUtility.UrlEncode(key),
            HttpUtility.UrlEncode(value));
    return Task.FromResult("?" + Join("&", values));
}