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

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

    Here's a fluent/lambda-ish way as an extension method (combining concepts in previous posts) that supports multiple values for the same key. My personal preference is extensions over wrappers for discover-ability by other team members for stuff like this. Note that there's controversy around encoding methods, plenty of posts about it on Stack Overflow (one such post) and MSDN bloggers (like this one).

    public static string ToQueryString(this NameValueCollection source)
    {
        return String.Join("&", source.AllKeys
            .SelectMany(key => source.GetValues(key)
                .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))))
            .ToArray());
    }
    

    edit: with null support, though you'll probably need to adapt it for your particular situation

    public static string ToQueryString(this NameValueCollection source, bool removeEmptyEntries)
    {
        return source != null ? String.Join("&", source.AllKeys
            .Where(key => !removeEmptyEntries || source.GetValues(key)
                .Where(value => !String.IsNullOrEmpty(value))
                .Any())
            .SelectMany(key => source.GetValues(key)
                .Where(value => !removeEmptyEntries || !String.IsNullOrEmpty(value))
                .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), value != null ? HttpUtility.UrlEncode(value) : string.Empty)))
            .ToArray())
            : string.Empty;
    }
    

提交回复
热议问题