Portable Class Library (PCL) Version Of HttpUtility.ParseQueryString

后端 未结 4 1265
天命终不由人
天命终不由人 2021-02-12 23:18

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.

4条回答
  •  野性不改
    2021-02-12 23:33

    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);
        }
    }
    

提交回复
热议问题