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

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

    A quick extension method based version:

    class Program
    {
        static void Main(string[] args)
        {
            var parameters = new List>
                                 {
                                     new KeyValuePair("A", "AValue"),
                                     new KeyValuePair("B", "BValue")
                                 };
    
            string output = "?" + string.Join("&", parameters.ConvertAll(param => param.ToQueryString()).ToArray());
        }
    }
    
    public static class KeyValueExtensions
    {
        public static string ToQueryString(this KeyValuePair obj)
        {
            return obj.Key + "=" + HttpUtility.UrlEncode(obj.Value);
        }
    }
    

    You could use a where clause to select which parameters get added to the string.

提交回复
热议问题