如何在 .NET 中将查询字符串解析为 NameValueCollection
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/68624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse a query string into a NameValueCollection in .NET
提问by Nathan Smith
I would like to parse a string such as p1=6&p2=7&p3=8into a NameValueCollection.
我想解析字符串,如p1=6&p2=7&p3=8成NameValueCollection。
What is the most elegant way of doing this when you don't have access to the Page.Requestobject?
当您无法访问Page.Request对象时,最优雅的方法是什么?
回答by Guy Starbuck
There's a built-in .NET utility for this: HttpUtility.ParseQueryString
有一个内置的 .NET 实用程序: HttpUtility.ParseQueryString
// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
You may need to replace querystringwith new Uri(fullUrl).Query.
您可能需要替换querystring为new Uri(fullUrl).Query.
回答by Scott Dorman
HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:
只要您在 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);
}
}
回答by James Skimming
A lot of the answers are providing custom examples because of the accepted answer's dependency on System.Web. From the Microsoft.AspNet.WebApi.ClientNuGet package there is a UriExtensions.ParseQueryString, method that can also be used:
由于接受的答案依赖于System.Web ,许多答案都提供了自定义示例。从Microsoft.AspNet.WebApi.ClientNuGet包有一个UriExtensions.ParseQueryString,方法还可以用于:
var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8");
NameValueCollection query = uri.ParseQueryString();
So if you want to avoid the System.Webdependency and don't want to roll your own, this is a good option.
因此,如果您想避免System.Web依赖项并且不想自己滚动,这是一个不错的选择。
回答by densom
I wanted to remove the dependency on System.Web so that I could parse the query string of a ClickOnce deployment, while having the prerequisites limited to the "Client-only Framework Subset".
我想删除对 System.Web 的依赖,以便我可以解析 ClickOnce 部署的查询字符串,同时将先决条件限制为“仅客户端框架子集”。
I liked rp's answer. I added some additional logic.
我喜欢 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;
}
回答by Josh Brown
I needed a function that is a little more versatile than what was provided already when working with OLSC queries.
在处理 OLSC 查询时,我需要一个比已经提供的功能更通用的函数。
- Values may contain multiple equal signs
- Decode encoded characters in both name and value
- Capable of running on Client Framework
- Capable of running on Mobile Framework.
- 值可能包含多个等号
- 解码名称和值中的编码字符
- 能够在客户端框架上运行
- 能够在移动框架上运行。
Here is my solution:
这是我的解决方案:
Public Shared Function ParseQueryString(ByVal uri As Uri) As System.Collections.Specialized.NameValueCollection
Dim result = New System.Collections.Specialized.NameValueCollection(4)
Dim query = uri.Query
If Not String.IsNullOrEmpty(query) Then
Dim pairs = query.Substring(1).Split("&"c)
For Each pair In pairs
Dim parts = pair.Split({"="c}, 2)
Dim name = System.Uri.UnescapeDataString(parts(0))
Dim value = If(parts.Length = 1, String.Empty,
System.Uri.UnescapeDataString(parts(1)))
result.Add(name, value)
Next
End If
Return result
End Function
It may not be a bad idea to tack <Extension()>on that too to add the capability to Uri itself.
将其<Extension()>添加到 Uri 本身也可能不是一个坏主意。
回答by jvenema
To do this without System.Web, without writing it yourself, and without additional NuGet packages:
要做到这一点System.Web,无需自己编写,无需额外的 NuGet 包:
- Add a reference to
System.Net.Http.Formatting - Add
using System.Net.Http; Use this code:
new Uri(uri).ParseQueryString()
- 添加引用
System.Net.Http.Formatting - 添加
using System.Net.Http; 使用此代码:
new Uri(uri).ParseQueryString()
https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx
https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx
回答by Amadeus Sánchez
If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uriextension method ParseQueryStringfound in System.Net.Http.
如果你想避免需要使用上的System.Web依赖HttpUtility.ParseQueryString,您可以使用Uri扩展方法ParseQueryString中发现的System.Net.Http。
Make sure to add a reference (if you haven't already) to System.Net.Httpin your project.
确保System.Net.Http在您的项目中添加一个引用(如果您还没有)。
Note that you have to convert the response body to a valid Uriso that ParseQueryString(in System.Net.Http)works.
请注意,您必须将响应正文转换为有效的,Uri以便ParseQueryString(in System.Net.Http) 工作。
string body = "value1=randomvalue1&value2=randomValue2";
// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
string urlBody = "http://localhost/query?" + body;
NameValueCollection coll = new Uri(urlBody).ParseQueryString();
回答by Thomas Levesque
I just realized that Web API Clienthas a ParseQueryStringextension method that works on a Uriand returns a HttpValueCollection:
我刚刚意识到Web API 客户端有一个ParseQueryString扩展方法,它适用于 aUri并返回 a HttpValueCollection:
var parameters = uri.ParseQueryString();
string foo = parameters["foo"];
回答by rp.
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 ] );
}
}
}
回答by alex1kirch
HttpUtility.ParseQueryString(Request.Url.Query)return is HttpValueCollection(internal class). It inherits from NameValueCollection.
HttpUtility.ParseQueryString(Request.Url.Query)返回是HttpValueCollection(内部类)。它继承自NameValueCollection.
var qs = HttpUtility.ParseQueryString(Request.Url.Query);
qs.Remove("foo");
string url = "~/Default.aspx";
if (qs.Count > 0)
url = url + "?" + qs.ToString();
Response.Redirect(url);

