在 C# 中构建具有多个 URL 参数的列表

Building a List with multiple URL Params in C#

我正在尝试构建一个通用函数,它将 运行 使用各种可能的 URL 参数的简单 HTTP Get 请求。 我希望能够接收灵活数量的字符串作为参数,并将它们作为 URL 参数一个一个地添加到请求中。 到目前为止,这是我的代码,我正在尝试构建一个列表,但由于某种原因,我无法找到一个有效的解决方案..

        public static void GetRequest(List<string> lParams)
    {
        lParams.Add(header1);
        string myURL = "";
        HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(myURL));
        WebReq.Method = "GET";
        HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
        Stream Answer = WebResp.GetResponseStream();
        StreamReader _Answer = new StreamReader(Answer);
        sContent = _Answer.ReadToEnd();
    }

谢谢!

我想你需要这个:

private static string CreateUrl(string baseUrl, Dictionary<string, string> args)
{
    var sb = new StringBuilder(baseUrl);
    var f = true;
    foreach (var arg in args)
    {
        sb.Append(f ? '?' : '&');
        sb.Append(WebUtility.UrlEncode(arg.Key) + '=' + WebUtility.UrlEncode(arg.Value));
        f = false;
    }
    return sb.ToString();
}

没有那么复杂的版本,有评论:

private static string CreateUrl(string baseUrl, Dictionary<string, string> parameters)
{
    var stringBuilder = new StringBuilder(baseUrl);
    var firstTime = true;

    // Going through all the parameters
    foreach (var arg in parameters)
    {
        if (firstTime)
        {
            stringBuilder.Append('?'); // first parameter is appended with a ? - www.example.com/index.html?abc=3
            firstTime = false; // All other following parameters should be added with a &
        }
        else
        {
            stringBuilder.Append('&'); // all  other parameters are appended with a & - www.example.com/index.html?abc=3&abcd=4&abcde=8
        }

        var key = WebUtility.UrlEncode(arg.Key); // Converting characters which are not allowed in the url to escaped values
        var value = WebUtility.UrlEncode(arg.Value); // Same goes for the value

        stringBuilder.Append(key + '=' + value); // Writing the parameter in the format key=value
    }

    return stringBuilder.ToString(); // Returning the url with parameters
}