简体   繁体   English

在查询字符串HttpClient.GetAsync()中传递List的最佳方法

[英]Best way to pass List in query string HttpClient.GetAsync()

I use HttpClient.GetAsync() method. 我使用HttpClient.GetAsync()方法。 I have a list of categories and want to pass it in query string. 我有一个类别列表,想在查询字符串中传递它。

 var categories = new List<int>() {1,2};

How can I pass List<int>/List<string> in query string? 如何在查询字符串中传递List<int>/List<string> For example, https://example.com/api?categories=1,2 例如, https://example.com/api?categories=1,2

Of course, can use foreach and StringBuilder . 当然可以使用foreachStringBuilder But maybe there is a better way to do this? 但是也许有更好的方法可以做到这一点?

For example, work with .PostAsync() and json content very convenient: 例如,使用.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 I work with Windows Phone 8. PS我使用Windows Phone 8。

If you are prepared to take a dependency on a library that supports URI Templates, like the one I created ( http://www.nuget.org/packages/Tavis.UriTemplates/ ) then you get all kinds of flexibility for creating URIs. 如果准备好依赖支持URI模板的库,例如我创建的库( http://www.nuget.org/packages/Tavis.UriTemplates/ ),那么您将获得创建URI的各种灵活性。 The full spec is here RFC6570 完整规格在这里RFC6570

You first create a URI template, 您首先创建一个URI模板,

var template = new UriTemplate("http://example.com/api{?categories}");

and you can set the parameter with either a simple string, a list of strings or a dictionary of string key/value pairs. 您可以使用简单字符串,字符串列表或字符串键/值对字典来设置参数。

 var idList = new string[] {"1", "4", "5", "7", "8"};
 template.SetParameter("id",idList);

and then you can resolve the parameters to create a full URI 然后您可以解析参数以创建完整的URI

  var uri = template.Resolve();
  Debug.Assert(uri == "http://example.com/api?categories=1,4,5,7,8");

The nice thing is that if you have other query parameters, or there are characters that need encoding, the URI template processor will take care of all of that for you too. 令人高兴的是,如果您有其他查询参数,或者有需要编码的字符,则URI模板处理器也将为您处理所有这些问题。

This extended test suite give you an idea of some of the crazy stuff that is supported. 这个扩展的测试套件使您对所支持的一些疯狂的东西有所了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM