如何将查询字符串解析为.NET中的NameValueCollection
时间:2020-03-05 18:54:58 来源:igfitidea点击:
我想将诸如p1 = 6&p2 = 7&p3 = 8之类的字符串解析为NameNameCollection中的内容。
当我们无法访问Page.Request
对象时,最优雅的方法是什么?
解决方案
回答
选中Request.QueryString.Keys以获取所有查询字符串参数的NameValueCollection。
回答
只需访问Request.QueryString。作为另一个答案提到的AllKeys只会为我们提供一系列的键。
回答
为此有一个内置的.NET实用程序:HttpUtility.ParseQueryString
// C# NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
我们可能需要将querystring
替换为new Uri(fullUrl).Query
。
回答
private void button1_Click( object sender, EventArgs e ) { string s = @"p1=6&p2=7&p3=8"; NameValueCollection nvc = new NameValueCollection(); foreach ( string vp in Regex.Split( s, "&" ) ) { string[] singlePair = Regex.Split( vp, "=" ); if ( singlePair.Length == 2 ) { nvc.Add( singlePair[ 0 ], singlePair[ 1 ] ); } } }
回答
只要我们在Web应用程序中,或者不介意包括对System.Web的依赖关系,HttpUtility.ParseQueryString都可以使用。另一种方法是:
NameValueCollection queryParameters = new NameValueCollection(); string[] querySegments = queryString.Split('&'); foreach(string segment in querySegments) { string[] parts = segment.Split('='); if (parts.Length > 0) { string key = parts[0].Trim(new char[] { '?', ' ' }); string val = parts[1].Trim(); queryParameters.Add(key, val); } }
回答
我想删除对System.Web的依赖关系,以便我可以解析ClickOnce部署的查询字符串,同时前提条件仅限于"仅客户端框架子集"。
我喜欢rp的答案。我添加了一些其他逻辑。
public static NameValueCollection ParseQueryString(string s) { NameValueCollection nvc = new NameValueCollection(); // remove anything other than query string from url if(s.Contains("?")) { s = s.Substring(s.IndexOf('?') + 1); } foreach (string vp in Regex.Split(s, "&")) { string[] singlePair = Regex.Split(vp, "="); if (singlePair.Length == 2) { nvc.Add(singlePair[0], singlePair[1]); } else { // only one key with no value specified in query string nvc.Add(singlePair[0], string.Empty); } } return nvc; }