我可以向uribuilder添加查询字符串的列表或数组吗



我正在使用UriBuilder为API端点创建url。

我需要为它添加一些查询字符串,我可以通过以下示例很好地做到这一点:

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();
}
}

这很简单也很好。但我需要相当多的查询字符串,并且根据调用函数的人的不同,我需要不同的数量。所以另一个解决方案可能是这样的:

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();
}
}

但我想知道是否有什么东西能让我感觉更";本地";。也许是创建一个带有键和值的dictionary,这样调用方就可以创建一个字典,而不是对其中的许多查询字符串进行硬编码?

我认为NameValueCollection可能适用于您提到的解决方案。您可以使用动态方法。

例如:

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));
}

最新更新