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

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

    The code below is taken off the HttpValueCollection implementation of ToString, via ILSpy, which gives you a name=value querystring.

    Unfortunately HttpValueCollection is an internal class which you only ever get back if you use HttpUtility.ParseQueryString(). I removed all the viewstate parts to it, and it encodes by default:

    public static class HttpExtensions
    {
        public static string ToQueryString(this NameValueCollection collection)
        {
            // This is based off the NameValueCollection.ToString() implementation
            int count = collection.Count;
            if (count == 0)
                return string.Empty;
    
            StringBuilder stringBuilder = new StringBuilder();
    
            for (int i = 0; i < count; i++)
            {
                string text = collection.GetKey(i);
                text = HttpUtility.UrlEncodeUnicode(text);
                string value = (text != null) ? (text + "=") : string.Empty;
                string[] values = collection.GetValues(i);
                if (stringBuilder.Length > 0)
                {
                    stringBuilder.Append('&');
                }
                if (values == null || values.Length == 0)
                {
                    stringBuilder.Append(value);
                }
                else
                {
                    if (values.Length == 1)
                    {
                        stringBuilder.Append(value);
                        string text2 = values[0];
                        text2 = HttpUtility.UrlEncodeUnicode(text2);
                        stringBuilder.Append(text2);
                    }
                    else
                    {
                        for (int j = 0; j < values.Length; j++)
                        {
                            if (j > 0)
                            {
                                stringBuilder.Append('&');
                            }
                            stringBuilder.Append(value);
                            string text2 = values[j];
                            text2 = HttpUtility.UrlEncodeUnicode(text2);
                            stringBuilder.Append(text2);
                        }
                    }
                }
            }
    
            return stringBuilder.ToString();
        }
    }
    

提交回复
热议问题