[英]Best way to pass List in query string HttpClient.GetAsync()
我使用HttpClient.GetAsync()
方法。 我有一个类别列表,想在查询字符串中传递它。
var categories = new List<int>() {1,2};
如何在查询字符串中传递List<int>/List<string>
? 例如, https://example.com/api?categories=1,2
当然可以使用foreach
和StringBuilder
。 但是也许有更好的方法可以做到这一点?
例如,使用.PostAsync()和json内容非常方便:
var categories = new List<int>() {1,2}; //init List
var parametrs = new Dictionary<string, object>();
parametrs.Add("categories", categories);
string jsonParams = JsonConvert.SerializeObject(parametrs); // {"categories":[1,2]}
HttpContent content = new StringContent(jsonParams, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(new Uri("https://example.com"), content);
PS我使用Windows Phone 8。
如果准备好依赖支持URI模板的库,例如我创建的库( http://www.nuget.org/packages/Tavis.UriTemplates/ ),那么您将获得创建URI的各种灵活性。 完整规格在这里RFC6570
您首先创建一个URI模板,
var template = new UriTemplate("http://example.com/api{?categories}");
您可以使用简单字符串,字符串列表或字符串键/值对字典来设置参数。
var idList = new string[] {"1", "4", "5", "7", "8"};
template.SetParameter("id",idList);
然后您可以解析参数以创建完整的URI
var uri = template.Resolve();
Debug.Assert(uri == "http://example.com/api?categories=1,4,5,7,8");
令人高兴的是,如果您有其他查询参数,或者有需要编码的字符,则URI模板处理器也将为您处理所有这些问题。
这个扩展的测试套件使您对所支持的一些疯狂的东西有所了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.