1

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.

3
  • Your code shows you're using JSON already to pass the content. Why not pass the list in the query string as JSON too? After all, JSON is a great way to represent data in a string. I asked a while ago if there'd be problems passing JSON in the URL and the results were encouraging. Commented May 8, 2014 at 16:05
  • Instead of a loop and StringBuilder, just use string.Join(",", categories). Commented May 8, 2014 at 16:07
  • @mason How can I pass json in query string using GetAsync()? Sorry, I don't quite understand. Commented May 8, 2014 at 16:15

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.