Reputation: 1901
I use HttpClient.GetAsync()
method. 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?
For example, https://example.com/api?categories=1,2
Of course, can use foreach
and StringBuilder
. But maybe there is a better way to do this?
For example, work with .PostAsync() and json content very convenient:
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);
P.S. I work with Windows Phone 8.
Upvotes: 1
Views: 10268
Reputation: 142222
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. The full spec is here RFC6570
You first create a URI template,
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
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.
This extended test suite give you an idea of some of the crazy stuff that is supported.
Upvotes: 0