Parse and modify a query string in .NET Core

后端 未结 6 634
無奈伤痛
無奈伤痛 2020-11-29 00:38

I am given an absolute URI that contains a query string. I\'m looking to safely append a value to the query string, and change an existing parameter.

I would prefer

6条回答
  •  Happy的楠姐
    2020-11-29 01:20

    This function return Dictionary and does not use Microsoft.xxx for compatibility

    Accepts parameter encoding in both sides

    Accepts duplicate keys (return last value)

    var rawurl = "https://emp.com/some/path?key1.name=a%20line%20with%3D&key2=val2&key2=valdouble&key3=&key%204=44#book1";
    var uri = new Uri(rawurl);
    Dictionary queryString = ParseQueryString(uri.Query);
    
    // queryString return:
    // key1.name, a line with=
    // key2, valdouble
    // key3, 
    // key 4, 44
    
    public Dictionary ParseQueryString(string requestQueryString)
    {
        Dictionary rc = new Dictionary();
        string[] ar1 = requestQueryString.Split(new char[] { '&', '?' });
        foreach (string row in ar1)
        {
            if (string.IsNullOrEmpty(row)) continue;
            int index = row.IndexOf('=');
            if (index < 0) continue;
            rc[Uri.UnescapeDataString(row.Substring(0, index))] = Uri.UnescapeDataString(row.Substring(index + 1)); // use Unescape only parts          
         }
         return rc;
    }
    

提交回复
热议问题