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

前端 未结 30 2497
借酒劲吻你
借酒劲吻你 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:20

    I went with the solution proposed by DSO (answered on Aug 2 '11 at 7:29), his solution does not require using HttpUtility. However, as per an article posted in Dotnetpearls, using a Dictionary is faster (in performance) than using NameValueCollection. Here is DSO's solution modified to use Dictionary in place of NameValueCollection.

        public static Dictionary QueryParametersDictionary()
        {
            var dictionary = new Dictionary();
            dictionary.Add("name", "John Doe");
            dictionary.Add("address.city", "Seattle");
            dictionary.Add("address.state_code", "WA");
            dictionary.Add("api_key", "5352345263456345635");
    
            return dictionary;
        }
    
        public static string ToQueryString(Dictionary nvc)
        {
            StringBuilder sb = new StringBuilder();
    
            bool first = true;
    
            foreach (KeyValuePair pair in nvc)
            {
                    if (!first)
                    {
                        sb.Append("&");
                    }
    
                    sb.AppendFormat("{0}={1}", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value));
    
                    first = false;
            }
    
            return sb.ToString();
        }
    

提交回复
热议问题