Is there a Portable Class Library (PCL) version Of HttpUtility.ParseQueryString contained in System.Web or some code I could use? I want to read a very complex URL.
You can also implement it like this:
public static class HttpUtility
{
public static Dictionary ParseQueryString(Uri uri)
{
var query = uri.Query.Substring(uri.Query.IndexOf('?') + 1); // +1 for skipping '?'
var pairs = query.Split('&');
return pairs
.Select(o => o.Split('='))
.Where(items => items.Count() == 2)
.ToDictionary(pair => Uri.UnescapeDataString(pair[0]),
pair => Uri.UnescapeDataString(pair[1]));
}
}
Here is a Unit test for that:
public class HttpParseQueryValuesTests
{
[TestCase("http://www.example.com", 0, "", "")]
[TestCase("http://www.example.com?query=value", 1, "query", "value")]
public void When_parsing_http_query_then_should_have_these_values(string uri, int expectedParamCount,
string expectedKey, string expectedValue)
{
var queryParams = HttpUtility.ParseQueryString(new Uri(uri));
queryParams.Count.Should().Be(expectedParamCount);
if (queryParams.Count > 0)
queryParams[expectedKey].Should().Be(expectedValue);
}
}