Get url parameters from a string in .NET

前端 未结 13 1843
一个人的身影
一个人的身影 2020-11-22 11:38

I\'ve got a string in .NET which is actually a url. I want an easy way to get the value from a particular parameter.

Normally, I\'d just use Request.Params[

13条回答
  •  感动是毒
    2020-11-22 11:43

    Here's another alternative if, for any reason, you can't or don't want to use HttpUtility.ParseQueryString().

    This is built to be somewhat tolerant to "malformed" query strings, i.e. http://test/test.html?empty= becomes a parameter with an empty value. The caller can verify the parameters if needed.

    public static class UriHelper
    {
        public static Dictionary DecodeQueryParameters(this Uri uri)
        {
            if (uri == null)
                throw new ArgumentNullException("uri");
    
            if (uri.Query.Length == 0)
                return new Dictionary();
    
            return uri.Query.TrimStart('?')
                            .Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(parameter => parameter.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
                            .GroupBy(parts => parts[0],
                                     parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
                            .ToDictionary(grouping => grouping.Key,
                                          grouping => string.Join(",", grouping));
        }
    }
    

    Test

    [TestClass]
    public class UriHelperTest
    {
        [TestMethod]
        public void DecodeQueryParameters()
        {
            DecodeQueryParametersTest("http://test/test.html", new Dictionary());
            DecodeQueryParametersTest("http://test/test.html?", new Dictionary());
            DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary { { "key", "bla/blub.xml" } });
            DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary { { "eins", "1" }, { "zwei", "2" } });
            DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary { { "empty", "" } });
            DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary { { "empty", "" } });
            DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary { { "key", "1" } });
            DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary { { "key", "value?" }, { "b", "c" } });
            DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary { { "key", "value=what" } });
            DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22",
                new Dictionary
                {
                    { "q", "energy+edge" },
                    { "rls", "com.microsoft:en-au" },
                    { "ie", "UTF-8" },
                    { "oe", "UTF-8" },
                    { "startIndex", "" },
                    { "startPage", "1%22" },
                });
            DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue", new Dictionary { { "key", "value,anotherValue" } });
        }
    
        private static void DecodeQueryParametersTest(string uri, Dictionary expected)
        {
            Dictionary parameters = new Uri(uri).DecodeQueryParameters();
            Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri);
            foreach (var key in expected.Keys)
            {
                Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri);
                Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri);
            }
        }
    }
    

提交回复
热议问题