Get url parameters from a string in .NET

前端 未结 13 1631
一个人的身影
一个人的身影 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<string, string> DecodeQueryParameters(this Uri uri)
        {
            if (uri == null)
                throw new ArgumentNullException("uri");
    
            if (uri.Query.Length == 0)
                return new Dictionary<string, string>();
    
            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<string, string>());
            DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>());
            DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary<string, string> { { "key", "bla/blub.xml" } });
            DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } });
            DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary<string, string> { { "empty", "" } });
            DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary<string, string> { { "empty", "" } });
            DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary<string, string> { { "key", "1" } });
            DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } });
            DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary<string, string> { { "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<string, string>
                {
                    { "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<string, string> { { "key", "value,anotherValue" } });
        }
    
        private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected)
        {
            Dictionary<string, string> 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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:48

    You can use the following workaround for it to work with the first parameter too:

    var param1 =
        HttpUtility.ParseQueryString(url.Substring(
            new []{0, url.IndexOf('?')}.Max()
        )).Get("param1");
    
    0 讨论(0)
  • 2020-11-22 11:49

    if you want in get your QueryString on Default page .Default page means your current page url . you can try this code :

    string paramIl = HttpUtility.ParseQueryString(this.ClientQueryString).Get("city");
    
    0 讨论(0)
  • 2020-11-22 11:50

    I used it and it run perfectly

    <%=Request.QueryString["id"] %>
    
    0 讨论(0)
  • 2020-11-22 11:53

    Or if you don't know the URL (so as to avoid hardcoding, use the AbsoluteUri

    Example ...

            //get the full URL
            Uri myUri = new Uri(Request.Url.AbsoluteUri);
            //get any parameters
            string strStatus = HttpUtility.ParseQueryString(myUri.Query).Get("status");
            string strMsg = HttpUtility.ParseQueryString(myUri.Query).Get("message");
            switch (strStatus.ToUpper())
            {
                case "OK":
                    webMessageBox.Show("EMAILS SENT!");
                    break;
                case "ER":
                    webMessageBox.Show("EMAILS SENT, BUT ... " + strMsg);
                    break;
            }
    
    0 讨论(0)
  • 2020-11-22 11:54

    For anyone who wants to loop through all query strings from a string

            foreach (var item in new Uri(urlString).Query.TrimStart('?').Split('&'))
            {
                var subStrings = item.Split('=');
    
                var key = subStrings[0];
                var value = subStrings[1];
    
                // do something with values
            }
    
    0 讨论(0)
提交回复
热议问题