Best way to convert query string to dictionary in C#

前端 未结 13 937
温柔的废话
温柔的废话 2020-12-24 04:28

I\'m looking for the simplest way of converting a query string from an HTTP GET request into a Dictionary, and back again.

I figure it\'s easier to carry out various

13条回答
  •  無奈伤痛
    2020-12-24 05:29

    I like the brevity of Jon Canning's answer, but in the interest of variety, here is another alternative to his answer, that would also work for restricted environments like Windows Phone 8, that lack the HttpUtility.ParseQueryString() utility:

        public static Dictionary ParseQueryString(String query)
        {
            Dictionary queryDict = new Dictionary();
            foreach (String token in query.TrimStart(new char[] { '?' }).Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
            {
                string[] parts = token.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == 2)
                    queryDict[parts[0].Trim()] = HttpUtility.UrlDecode(parts[1]).Trim();
                else
                    queryDict[parts[0].Trim()] = "";
            }
            return queryDict;
        }
    

    Actually, a useful improvement to Canning's answer that take care of decoding url-encoded values (like in the above solution) is:

        public static Dictionary ParseQueryString2(String query)
        {
           return Regex.Matches(query, "([^?=&]+)(=([^&]*))?").Cast().ToDictionary(x => x.Groups[1].Value, x => HttpUtility.UrlDecode( x.Groups[3].Value ));
        }
    

提交回复
热议问题