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
HttpUtility.ParseQueryString()
parses query string into a NameValueCollection
object, converting the latter to an IDictionary<string, string>
is a matter of a simple foreach
. This, however, might be unnecessary since NameValueCollection
has an indexer, so it behaves pretty much like a dictionary.
Same as Sean, but with Linq (and a function you can copy and paste):
public static Dictionary<string, string> ParseQueryString(string queryString)
{
var nvc = HttpUtility.ParseQueryString(queryString);
return nvc.AllKeys.ToDictionary(k => k, k => nvc[k]);
}
Also, the question asked how to get it back into a query string:
public static string CreateQueryString(Dictionary<string, string> parameters)
{
return string.Join("&", parameters.Select(kvp =>
string.Format("{0}={1}", kvp.Key, HttpUtility.UrlEncode(kvp.Value))));
}
In ASP.NET Core, use ParseQuery.
var query = HttpContext.Request.QueryString.Value;
var queryDictionary = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(query);
Just had to do this for a mono compatible solution
Regex.Matches(queryString, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => x.Groups[3].Value)
How about HttpUtility.ParseQueryString?
Just add a reference to System.Web.dll
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<string, string> ParseQueryString(String query)
{
Dictionary<String, String> queryDict = new Dictionary<string, string>();
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<string, string> ParseQueryString2(String query)
{
return Regex.Matches(query, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => HttpUtility.UrlDecode( x.Groups[3].Value ));
}