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

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

    Combined the top answers to create an anonymous object version:

    var queryString = HttpUtility2.BuildQueryString(new
    {
        key2 = "value2",
        key1 = "value1",
    });
    

    That generates this:

    key2=value2&key1=value1

    Here's the code:

    public static class HttpUtility2
    {
        public static string BuildQueryString(T obj)
        {
            var queryString = HttpUtility.ParseQueryString(string.Empty);
    
            foreach (var property in TypeDescriptor.GetProperties(typeof(T)).Cast())
            {
                var value = (property.GetValue(obj) ?? "").ToString();
                queryString.Add(property.Name, value);
            }
    
            return queryString.ToString();
        }
    }
    

提交回复
热议问题