How to build a query string for a URL in C#?

前端 未结 30 2507
借酒劲吻你
借酒劲吻你 2020-11-22 01:55

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are so

30条回答
  •  情歌与酒
    2020-11-22 02:40

    Here's my late entry. I didn't like any of the others for various reasons, so I wrote my own.

    This version features:

    • Use of StringBuilder only. No ToArray() calls or other extension methods. It doesn't look as pretty as some of the other responses, but I consider this a core function so efficiency is more important than having "fluent", "one-liner" code which hide inefficiencies.

    • Handles multiple values per key. (Didn't need it myself but just to silence Mauricio ;)

      public string ToQueryString(NameValueCollection nvc)
      {
          StringBuilder sb = new StringBuilder("?");
      
          bool first = true;
      
          foreach (string key in nvc.AllKeys)
          {
              foreach (string value in nvc.GetValues(key))
              {
                  if (!first)
                  {
                      sb.Append("&");
                  }
      
                  sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
      
                  first = false;
              }
          }
      
          return sb.ToString();
      }
      

    Example Usage

            var queryParams = new NameValueCollection()
            {
                { "x", "1" },
                { "y", "2" },
                { "foo", "bar" },
                { "foo", "baz" },
                { "special chars", "? = &" },
            };
    
            string url = "http://example.com/stuff" + ToQueryString(queryParams);
    
            Console.WriteLine(url);
    

    Output

    http://example.com/stuff?x=1&y=2&foo=bar&foo=baz&special%20chars=%3F%20%3D%20%26
    

提交回复
热议问题