我使用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);
附:我使用Windows Phone 8.
您的代碼顯示您已經使用JSON傳遞內容。爲什麼不將查詢字符串中的列表作爲JSON傳遞?畢竟,JSON是用字符串表示數據的好方法。我剛纔問過[如果在URL中傳遞JSON時會出現問題](http://stackoverflow.com/questions/22852270/potential-problems-with-passing-json-in-url),結果令人鼓舞。 – mason
而不是循環和'StringBuilder',只需使用'string.Join(「,」,categories)'。 –
@mason如何使用GetAsync()在查詢字符串中傳遞json?對不起,我不太明白。 – Alexandr