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

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

    Just wanted to throw in my 2 cents:

    public static class HttpClientExt
    {
        public static Uri AddQueryParams(this Uri uri, string query)
        {
            var ub = new UriBuilder(uri);
            ub.Query = string.IsNullOrEmpty(uri.Query) ? query : string.Join("&", uri.Query.Substring(1), query);
            return ub.Uri;
        }
    
        public static Uri AddQueryParams(this Uri uri, IEnumerable query)
        {
            return uri.AddQueryParams(string.Join("&", query));
        } 
    
        public static Uri AddQueryParams(this Uri uri, string key, string value)
        {
            return uri.AddQueryParams(string.Join("=", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)));
        }
    
        public static Uri AddQueryParams(this Uri uri, params KeyValuePair[] kvps)
        {
            return uri.AddQueryParams(kvps.Select(kvp => string.Join("=", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value))));
        }
    
        public static Uri AddQueryParams(this Uri uri, IDictionary kvps)
        {
            return uri.AddQueryParams(kvps.Select(kvp => string.Join("=", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value))));
        }
    
        public static Uri AddQueryParams(this Uri uri, NameValueCollection nvc)
        {
            return uri.AddQueryParams(nvc.AllKeys.SelectMany(nvc.GetValues, (key, value) => string.Join("=", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))));
        }
    }
    

    The docs say that uri.Query will start with a ? if it's non-empty and you should trim it off if you're going to modify it.

    Note that HttpUtility.UrlEncode is found in System.Web.

    Usage:

    var uri = new Uri("https://api.del.icio.us/v1/posts/suggest").AddQueryParam("url","http://stackoverflow.com")
    

提交回复
热议问题