如何在url中传递可变数量的参数

时间:2015-11-22 07:02:43

标签: c# url windows-phone

你好我试图在HttpWebRequest网址中传递可变数量的参数。到目前为止,我的方法是 -

public static async Task<ObservableCollection<Anime>> RequestsAnime(string accessToken, int page = 0, params string[] optionals)  // All Anime
    {
        JsonWebClient client = new JsonWebClient();

        string baseUri = "https://anilist.co/api/browse/anime?access_token=" + accessToken;
        string completeUri = "";

        string parameters = "";

        if (optionals != null)
        {
            parameters = CollectionUtils.ToStringFromArray(optionals);
            completeUri = baseUri + parameters;
        }

        if (page != 0)
        {
            completeUri = baseUri + "&page=" + page;
        }
        HttpWebRequest reqForToken = HttpWebRequest.CreateHttp(completeUri);
        reqForToken.Method = "GET";
        var respToken = await client.DoRequestJsonAsync<ObservableCollection<Anime>>(reqForToken);

        return respToken;
    }

ToStringFromArray函数

public static string ToStringFromArray(string[] arrayString)
    {
        string result = string.Join("", arrayString);
        return result;
    }

RequestsAnime Calling

string[] ds = new string[] { "&status", "=active", "&season","=fall" };
var nm = await Requests.CreateMultipleTasksAsync(ds);

CreateMultipleTaskAsync调用

 public static async Task<ObservableCollection<Anime>> CreateMultipleTasksAsync(int page=0 ,params string[] optionals)
    {
        Task<Auth> download1 = RequestsAuth();

        Auth length1 = await download1;

        Task<ObservableCollection<Anime>> download2 = RequestsAnime(download1.Result.Access_token,page, optionals);

        var animeList = await download2;

        return animeList;
    }

我知道这是一种笨拙的方式。我需要知道一个更好的解决方案。我的目标是 -

  1. 在网址
  2. 中传递可变数量的参数
  3. 使用“&amp;”附加参数和“=”

1 个答案:

答案 0 :(得分:0)

我建议您将所有查询字符串参数放在Dictionary

var parameters = new Dictionary<string, string>
{
    { "status", "active" },
    { "season", "fall" }
};

然后,您可以调用以下方法生成有效的查询字符串(请注意对Uri.EscapeDataString的调用:

string CreateQueryString(Dictionary<string, string> parameters)
{
    return String.Join("&", parameters
        .Select(param => String.Format("{0}={1}", 
            Uri.EscapeDataString(param.Key), 
            Uri.EscapeDataString(param.Value)))
        .ToArray());
}

只需将queryString附加到baseUri

completeUri = baseUri + "&" + CreateQueryString(parameters);